Class 23 of 37 • Advance Shell Script \t\t\t\t

Command Line Arguments in Linux Shell Scripting - Positional Parameters & Flags

Passing input arguments into a Bash shell script makes programs dynamic, reusable, and automated. Just like compiled C programs accept int argc, char *argv[], shell scripts read command-line inputs through reserved Positional Parameters assigned automatically by the shell interpreter during invocation.

Special Positional Parameters in Linux

The shell stores arguments in numbered positional variables starting from $1 for the first argument. The script's own executable name is stored in $0.

Variable

Meaning & Description

$0

Name of the shell script being executed (as invoked from command line).

$1, $2, ... $9

The 1st through 9th command-line arguments passed to the script.

${10}, ${11}

Arguments beyond the 9th position. Curly braces ${...} are mandatory.

$#

Total count of arguments passed to the script (excluding $0).

$*

All command-line arguments joined together as a single combined string.

$@

All command-line arguments represented as individually quoted words (recommended for loops).

$?

Exit status of the most recently executed command (0 = success, non-zero = error).

$$

Process ID (PID) of the currently running shell script instance.

$!

Process ID (PID) of the most recently triggered background job.

Basic Argument Handling Example

Here is a practical script demonstrating argument checking, comparison, and displaying total parameters:

#!/bin/bash
# Script Name: demo_args.sh
# Demonstrates basic command-line argument processing

echo "Script executed: $0"
echo "Total arguments passed: $#"

# Validate that at least two numbers were supplied
if [ $# -lt 2 ]; then
    echo "Error: Missing arguments."
    echo "Usage: $0 <number1> <number2>"
    exit 1
fi

echo "First argument  (\$1) : $1"
echo "Second argument (\$2) : $2"

# Compare the two numeric arguments (Note the spaces inside brackets!)
if [ "$1" -gt "$2" ]; then
    echo "Result: $1 is greater than $2"
elif [ "$1" -lt "$2" ]; then
    echo "Result: $2 is greater than $1"
else
    echo "Result: Both numbers are equal ($1 == $2)"
fi

Running the Script from Terminal

$ chmod +x demo_args.sh
$ ./demo_args.sh 45 20
Script executed: ./demo_args.sh
Total arguments passed: 2
First argument  ($1) : 45
Second argument ($2) : 20
Result: 45 is greater than 20

The Crucial Difference: "$*" vs "$@"

One of the most frequently asked viva and interview questions is the distinction between "$*" and "$@" when enclosed in quotes:

  • "$*": Concatenates all arguments into a single string separated by the first character of $IFS (usually a space). Example: "$1 $2 $3".
  • "$@": Expands each argument into an individual quoted word: "$1" "$2" "$3". It preserves whitespace inside individual parameters!
#!/bin/bash
# Demonstrating "$*" vs "$@"

echo "--- Iterating over \"\$*\" ---"
for item in "$*"; do
    echo "Item: $item"
done

echo "--- Iterating over \"\$@\" ---"
for item in "$@"; do
    echo "Item: $item"
done

Output when running ./test.sh "Apple Pie" "Banana Shake":

--- Iterating over "$*" ---
Item: Apple Pie Banana Shake
--- Iterating over "$@" ---
Item: Apple Pie
Item: Banana Shake

Processing Variable Arguments with shift

The built-in shift command moves the argument list to the left by one position. $2 becomes $1, $3 becomes $2, and $# is decremented by 1. This is the classic UNIX pattern to iterate through an arbitrary number of inputs:

#!/bin/bash
# sum_all.sh: Calculates the sum of any number of command line numbers
sum=0
count=$#

while [ $# -gt 0 ]; do
    sum=$(( sum + $1 ))
    shift   # Shift arguments left by 1 position
done

echo "Sum of $count numbers is: $sum"

Parsing Script Options & Flags using getopts

Real-world Linux command-line tools take flags like -f filename or -v. In shell scripting, the standard POSIX utility getopts provides clean option parsing:

#!/bin/bash
# getopts_demo.sh: Professional option parsing

verbose=false
filename=""

# Syntax: getopts "options" variable
# A colon (:) after an option flag means that flag expects an argument
while getopts "vf:h" opt; do
    case "$opt" in
        v)
            verbose=true
            ;;
        f)
            filename="$OPTARG"
            ;;
        h)
            echo "Usage: $0 [-v] [-f filename]"
            exit 0
            ;;
        \?)
            echo "Invalid option: -$OPTARG" >&2
            exit 1
            ;;
    esac
done

if [ "$verbose" = true ]; then
    echo "[VERBOSE MODE ENABLED]"
fi

if [ -n "$filename" ]; then
    echo "Processing target file: $filename"
else
    echo "No file specified. Use -f <filename>"
fi

Lab Practice: Multi-Operation Command-Line Calculator

Problem: Write a shell script that accepts three arguments: operator (add, sub, mul, div), num1, and num2, and prints the result with complete argument validation.

#!/bin/bash
# calculator.sh

if [ $# -ne 3 ]; then
    echo "Error: Exactly 3 arguments required."
    echo "Usage: $0 <operation: add|sub|mul|div> <num1> <num2>"
    exit 1
fi

op=$1
n1=$2
n2=$3

case "$op" in
    add)
        ans=$(( n1 + n2 ))
        echo "$n1 + $n2 = $ans"
        ;;
    sub)
        ans=$(( n1 - n2 ))
        echo "$n1 - $n2 = $ans"
        ;;
    mul)
        ans=$(( n1 * n2 ))
        echo "$n1 * $n2 = $ans"
        ;;
    div)
        if [ "$n2" -eq 0 ]; then
            echo "Error: Division by zero is prohibited."
            exit 2
        fi
        ans=$(( n1 / n2 ))
        echo "$n1 / $n2 = $ans"
        ;;
    *)
        echo "Unknown operation: $op. Choose add, sub, mul, or div."
        exit 3
        ;;
esac

Frequently Asked Questions (FAQs)

When quoted, "$*" combines all arguments into a single string separated by spaces, whereas "$@" preserves each argument as an independent quoted word, preventing unintended word-splitting on parameters containing spaces.
Use curly braces: ${10}, ${11}, ${12}. Without braces, $10 is evaluated as $1 concatenated with the literal digit 0.
$? holds the exit status code of the last executed command. By convention in Linux, 0 denotes success, while any non-zero value (such as 1, 2, or 127) indicates an error or failure.
shift shifts all positional parameters leftward by one position. $2 moves to $1, $3 moves to $2, and $# decreases by 1.

Next Step in Your Linux Learning Path:

Master substring slicing, pattern trimming, and search-replace in Class 24: String Manipulation.

Continue to Class 24: String Manipulation → Previous: ← Arrays | Full Syllabus

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!