How to parse input arguments with tokens in Bash script
Parse input or command line arguments in Bash script
Bash script will take input values and produces output values. We often pass input arguments to the bash script and they should be passed in the same order as required by the program. We can ignore order of the arguments by passing tokens (identifier or label or tag) along with input arguments. So, we know the meaning of each input arguments with the help of tokens.
Syntax to parse the input arguments in Bash
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
while [[ $# -gt 0 ]] do case $1 in -token1) command1 shift ;; -token2) command2 shift ;; -token3) command3 shift ;; *) command4 exit 1 ;; esac shift done |
Example to parse the input arguments in Bash script
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
$cat parse_args.sh #!/usr/bin/bash while [[ $# -gt 0 ]] do case $1 in -n) echo "Entered number: $2" shift ;; -l) echo "Entered letter: $2" shift ;; -s) echo "Entered symbol: $2" shift ;; *) echo "No number or letter or symbol entered" exit 1 ;; esac shift done $chmod +x parse_args.sh |
Loop through arguments using while loop
While loop will execute until number of arguments last. $# will hold number of input arguments passed to the program. While loop will execute the commands in the same order as placed between do and done block.
Match the arguments in case statement
Case statement will search the given value in each option and execute the commands under the option if match found. Case statement will execute commands in the same order until end block esac(reverse of case) is found.
Shift the arguments to the left
Shift will move input argument from right to left. That means first argument(starting from left) will disappear and second argument will become first. Two semicolons(;;) will force search operation stops if first match found. * will match all values except the ones explicitly declared(-n,-l,-s) and we are exiting our program with return code of 1. $? Will hold return code of previous command.
Chmod command to make file executable
Chmod is used to make our file executable. Chmod means change mode. +x means grant execute privilege. After this command, we can run this script without using sh and bash commands
Output
Recommended Articles