Jason Swett
Jason Swett

Reputation: 45074

How to handle missing args in shell script

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.

Upvotes: 43

Views: 55192

Answers (5)

Typical shell scripts begin by parsing the options and arguments passed on the command line.

The number of positional parameters (arguments) is stored in the # special parameter:

#

($#) Expands to the number of positional parameters in decimal.

Simple example

For example, if your scripts requires exactly 3 arguments, you can test 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"

Handle missing arguments by printing a message and returning an exit code

  • echo 1>&2 "$0: not enough arguments": The echo command is used to print text to the output. The following arguments are as follows:

    1. The output is redirected (>&) from standard output (denoted by file descriptor 1) to standard error (file descriptor 2).
    2. The message printed is specified in double-quotes as "$0: not enough arguments". The special parameter $0 is expanded to the name of the shell script (e.g. if you invoked the script like ./my_script.sh the message will start with this as expansion for $0).
  • exit 2: The built-in command exit terminates the script execution. The integer argument is the return value of the script, here 2 is commonly used to indicate an error:

    • 0: to indicate success and a small positive integer to indicate failure.
    • 1: by common convention means “not found” (think of the grep command)
    • 2: means “unexpected error” (unrecognized option, invalid input file name, etc.).

Advanced command-line parsing

If your script takes options (like -x), use special utilities like getopts to parse arguments and options.

See also

Upvotes: 74

ThorSummoner
ThorSummoner

Reputation: 18089

In my case I was using GIT_SSH_COMMAND which didn't like -o KEY Value, it wants

ssh -o KEY=value

ref https://github.com/fish-shell/fish-shell/issues/1299

Upvotes: -2

Markus N.
Markus N.

Reputation: 330

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.

Upvotes: 22

codeape
codeape

Reputation: 100766

The nounset option will make bash treat unset variables and parameters as an error.

Example script (myscript.sh):

#!/bin/bash
set -o nounset

echo First argument: $1
echo OK

Example:

$ ./myscript.sh; echo $?
./myscript.sh: line 4: $1: unbound variable
1
$ ./myscript.sh foo; echo $?
First argument: foo
OK
0

Upvotes: 17

ennuikiller
ennuikiller

Reputation: 46965

getopts is useful here: getopts

Upvotes: 6

Related Questions