bash:commands:command_line_arguments
This is an old revision of the document!
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" </code> Run this script with two additional parameters after its name. <code bash> ./test.sh Hello Peter </code> <WRAP info> **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. </WRAP> ---- ===== Getting Arguments with Names ===== The below example shows how to get command-line arguments with their names. <file bash 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:
./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.1611680565.txt.gz · Last modified: 2021/01/26 17:02 by peter