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

Example to parse the input arguments in Bash script

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


Recommended Articles