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.
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 |
|---|---|
|
Name of the shell script being executed (as invoked from command line). |
|
The 1st through 9th command-line arguments passed to the script. |
|
Arguments beyond the 9th position. Curly braces |
|
Total count of arguments passed to the script (excluding |
|
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. |
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
$ 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
"$*" 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
shiftThe 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"
getoptsReal-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
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
"$*" 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.
${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.
Master substring slicing, pattern trimming, and search-replace in Class 24: String Manipulation.
Continue to Class 24: String Manipulation → Previous: ← Arrays | Full Syllabus