skip to content »

Validating command line arguments in shell script

validating command line arguments in shell script-45

‘getopts’ function is used with while loop to read command line argument options and argument values.

for example let’s create & execute the test script with some parameters : Our first file just have a ls command and echo of exist status: #! on execution , it gives 0 as exist status: ./letters osmodule rpms testfile txt1 Exit status is : 0 Our Second file just have a misspelled ls command and echo of exist status: #!Bash Shell has several special positional parameters which can be referenced but can not be assigned.These bash parameters are used to process command line arguments in a bash shell script, to get process status, exit status and options flag.One is by using argument variables and another is by using getopts function.How you can handle command line arguments is shown in this tutorial. The main script file name is stored in $0 which receives argument values from command line arguments.When you need to send simple values in a script then it is better to use argument variables.

But if you want to send data in a formatted way then it is better to use getopts function to retrieve argument values.

Options are single letters with a dash before it.#!

/bin/bash while [ -n "$1" ]; do # while loop starts case "$1" in -a) echo "-a option passed" ;; # Message for -a option -b) echo "-b option passed" ;; # Message for -b option -c) echo "-c option passed" ;; # Message for -c option *) echo "Option $1 not recognized" ;; # In case you typed a different option other than a,b,c esac shift done Sometimes you need to use options and parameters in the same script. By doing this, you are telling the bash where are the parameters and where are the options.

case statement is used to match the particular option and store the argument value in a variable. Run the file with the following options and argument values.

Here, p100 is the value of -i option, ‘Hot Cake’ is the value of -n option, ’′ is the value of -m option and ’′ is the value of -e option.

And here is the list of the common options:-a List all items.-c Get count of items.-d Output directory.-e Expands items.-f To specify a file.-h To show help page.-i To ignore character case.-l To list a text.-n To say no for a question.-o To send output to a file or so.-q Keep silent don’t ask the user.-r To process something recursively.-s Stealth mode.-v Verbose mode.-x Specify executable.-y To say yes without prompting the user.