Getting arguments directly from the command shell can be beneficial in a number of cases.
#!/bin/bash echo "Total arguments : $#" echo "First Argument = $1" echo "Second Argument = $2"
Run this script with two additional parameters after its name.
./test.sh Hello Peter
NOTE: $1 is used for accessing the first argument, $2 for the second, and so on.
The $# is used for getting the total number of arguments.
The below example shows how to get command-line arguments with their names.
#!/bin/bash for arg in "$@" do index=$(echo $arg | cut -f1 -d=) val=$(echo $arg | cut -f2 -d=) case $index in X) x=$val;; Y) y=$val;; *) esac done ((result=x+y)) echo "X+Y=$result"
Run this script with two additional parameters after its name.
./test.sh X=44 Y=100
returns
X+Y=144
NOTE: The arguments here are stored inside ‘$@‘ and the script fetches them using the Linux cut command.