bash:commands:command_line_arguments
BASH - Commands - Command Line Arguments
Getting arguments directly from the command shell can be beneficial in a number of cases.
- test.sh
#!/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.
Getting Arguments with Names
The below example shows how to get command-line arguments with their names.
- test.sh
#!/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.
bash/commands/command_line_arguments.txt · Last modified: 2021/01/26 17:03 by peter