Positional Parameters in Unix OS and Shell Programming
Positional Parameters in Unix OS and Shell Programming
In Unix and Unix-like operating systems, positional parameters are variables that hold the
arguments or input passed to a script or command. These parameters are numbered, allowing
you to access and manipulate them easily in shell scripts.
Here’s a breakdown:
• $1, $2, ..., $N: Refers to the first, second, ..., Nth argument passed to the script.
$0 is ./myscript.sh
$1 is arg1
$2 is arg2
$3 is arg3
Special Parameters:
• $@: Expands to all arguments but treats each argument as a separate word.
• "$@": Useful in loops; it treats each argument as a separate quoted string, unlike $*.
• $@: Treats each argument separately. When quoted, each argument is individually
quoted and separated.
Examples
# Using "$@"
done
# Using "$*"
done
In this example, "$@" iterates over each argument separately, while "$*" treats all arguments as
one string.
Unix shell script for addition of two numbers using user input
read num1
read num2
sum=$((num1 + num2))
When executed, it will ask for two numbers and then display the sum.
Unix shell script for addition of two numbers using positional parameters
if [ $# -ne 2 ]; then
exit 1
fi
sum=$(($1 + $2))
if [ $# -ne 2 ]; then
exit 1
fi
shift
if [ $# -ne 2 ]; then
exit 1
fi
sum=$(( $1 + $2 ))