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.
$# : 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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With