BudiBadu Logo
Samplebadu

Shell Script by Example: Positional Parameters

Bash 5.x

Accessing script arguments with this code example demonstrating special variables like $0 for script name, $1-$9 for arguments, $# for argument count, $@ for all arguments, the shift command, and $? for exit status.

Code

#!/bin/bash

echo "Script name: $0"
echo "First argument: $1"
echo "Second argument: $2"
echo "Total arguments: $#"

# Iterate over all arguments
echo "All arguments:"
for arg in "$@"; do
    echo "- $arg"
done

# Shift arguments
echo "Shifting..."
shift
echo "First argument is now: $1"

# Special variable $? (Exit status of last command)
ls /nonexistent
echo "Exit status: $?" # 2 (or similar error code)

Explanation

Positional parameters are special variables that hold arguments passed to the script or function. $1 through $9 represent the first nine arguments, with 10 and beyond requiring braces. $0 contains the script name or path as invoked. $# holds the total argument count, useful for validating that the correct number of arguments was provided. These parameters are fundamental to creating flexible, parameterized scripts.

To handle an unknown number of arguments, use $@ or $*. The quoted form "$@" is best practice as it expands to all arguments individually while preserving whitespace within each argument. For example, if called with script.sh "file one.txt" "file two.txt", "$@" correctly treats these as two arguments. In contrast, "$*" expands to a single string with all arguments joined by the first character of IFS (typically a space).

The shift command removes the first positional parameter and shifts all others down by one position, so $2 becomes $1, $3 becomes $2, and so on. This is commonly used in while loops to process command-line flags and options sequentially. You can also use shift n to shift by n positions at once. The special variable $? contains the exit status of the most recently executed foreground command, essential for error handling and conditional logic based on command success or failure.

Code Breakdown

3
$0 contains the script name or path as it was invoked.
6
$# expands to the total count of arguments passed to the script.
10
"$@" expands to all arguments as separate quoted strings.
16
shift discards $1 and moves all arguments left by one position.