</>
Skip to content
Bash lessons (16/29)

Bash — Arguments

Positional parameters

#!/bin/bash

echo "Script: $0"
echo "First arg: $1"
echo "Second arg: $2"
echo "All args: $@"
echo "Number of args: $#"

Default values

#!/bin/bash

name="${1:-World}"
echo "Hello, $name!"

Shift

#!/bin/bash

while [ $# -gt 0 ]; do
    echo "Processing: $1"
    shift
done

Named arguments

#!/bin/bash

while [[ $# -gt 0 ]]; do
    case $1 in
        -n|--name)
            name="$2"
            shift 2
            ;;
        -a|--age)
            age="$2"
            shift 2
            ;;
        *)
            echo "Unknown: $1"
            shift
            ;;
    esac
done

echo "Name: $name, Age: $age"

Mini Practice

Write Bash code that:

  1. Prints all arguments
  2. Uses default values for missing arguments
  3. Processes arguments with shift
  4. Handles named arguments with a case statement

Up Next

In the next lesson, you'll learn about Exit Codes — returning status from scripts.

Related Topics

Frequently Asked Questions about Arguments

What is Arguments in Bash?

Arguments is a fundamental concept in Bash. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Arguments?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Arguments.

Why is Arguments important in Bash?

Arguments is essential for Bash development. Understanding this concept will help you write better code and solve real-world problems more effectively.