Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle missing args in shell script

Tags:

shell

What's the "right" way to handle missing arguments in a shell script? Is there a pre-canned way to check for this and then throw an exception? I'm an absolute beginner.

like image 394
Jason Swett Avatar asked Oct 15 '10 19:10

Jason Swett


People also ask

What is $# in shell script?

$# : This variable contains the number of arguments supplied to the script. $? : The exit status of the last command executed. Most commands return 0 if they were successful and 1 if they were unsuccessful. Comments in shell scripting start with # symbol.

What is $@ in bash script?

bash [filename] runs the commands saved in a file. $@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc. Place variables in quotes if the values might have spaces in them.

What does $() mean in bash?

Dollar sign $ (Variable) The dollar sign before the thing in parenthesis usually refers to a variable. This means that this command is either passing an argument to that variable from a bash script or is getting the value of that variable for something.


2 Answers

Typical shell scripts begin by parsing the options and arguments passed on the command line. The number of arguments is stored in the # parameter, i.e., you get it with $#. For example, if your scripts requires exactly three arguments, you can do something like this:

if [ $# -lt 3 ]; then   echo 1>&2 "$0: not enough arguments"   exit 2 elif [ $# -gt 3 ]; then   echo 1>&2 "$0: too many arguments"   exit 2 fi # The three arguments are available as "$1", "$2", "$3" 

The built-in command exit terminates the script execution. The integer argument is the return value of the script: 0 to indicate success and a small positive integer to indicate failure (a common convention is that 1 means “not found” (think grep) and 2 means “unexpected error” (unrecognized option, invalid input file name, ...)).

If your script takes options (like -x), use getopts.

like image 110
Gilles 'SO- stop being evil' Avatar answered Sep 23 '22 15:09

Gilles 'SO- stop being evil'


Example script (myscript.sh):

#!/bin/bash  file1=${1?param missing - from file.} file2=${2?param missing - to file.}   [...] 

Example:

$ ./myscript.sh file1  ./myscript.sh: line 4: 2: param missing - to file. 
like image 20
Markus N. Avatar answered Sep 19 '22 15:09

Markus N.