Skip to content
Tutorials Center
My learning

Topics

Lesson 42 of 95 ยท Shell Scripting

Script Arguments and Options

Handle script arguments in Bash: positional parameters, $#, shift, getopts for short options, a loop for long options, validation, usage messages and exit codes.

A script that does one fixed thing is a toy. A script that takes arguments is a tool: backup.sh /home/ada, convert.sh --format png photo.jpg, deploy.sh -v staging. The values after the script name arrive in the script as numbered variables, and a few conventions (options start with a dash, --help prints usage, a bad call exits with status 2) make your script feel like every other command on the system.

In this lesson you will read positional parameters, walk through them with shift, parse short options with the getopts builtin, parse long options with a loop, validate everything, print a helpful usage message, and finish with a small command-line template you can copy into your own scripts. It builds on Variables, Quoting and Conditionals.

Positional parameters

When you run ./greet.sh Ada Lovelace, the shell stores the words after the script name in special variables:

Variable Meaning
$0 The name the script was called by (./greet.sh)
$1, $2, ... The first, second, ... argument. Above $9 you must write braces: ${10}
$# How many arguments there are (not counting $0)
"$@" All arguments, each one kept as a separate word
$* All arguments joined into one string (unquoted: split again by the shell)
TEXT
  ./greet.sh   Ada   "Grace Hopper"   --loud
      |         |          |             |
     $0        $1         $2            $3        $# = 3
                          \_______ one argument, because it was quoted
Bash Reading $0, $1, $# and the whole list

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Two things to notice. "Grace Hopper" stayed one argument because the caller quoted it; the script cannot know what the user meant, it only sees the result. And with no arguments, $1 is simply empty, no error, which is why you must check $# yourself.

"$@" versus $*

The difference matters as soon as an argument contains a space. "$@" expands to one word per argument, exactly as given. $* and "$*" flatten them.

Bash At-sign keeps arguments apart, star glues them together

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

set -- replaces the positional parameters, a handy trick for experiments. The rule you should memorise: use "$@" whenever you pass your arguments along to another command. The other three forms re-split on spaces and break "red apple" into two words. The one good use of "$*" is joining with the first character of IFS, as in the last line.

Checking how many arguments you got

Most scripts need a fixed number of required arguments. Check $# first and fail early with a clear message and a non-zero exit status.

Bash Requiring arguments and failing politely

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Three habits are visible here:

  • Error and usage messages go to standard error (>&2), so they do not pollute the output that another program might be reading.
  • ${0##*/} strips the directory from $0, leaving just the script name (see Parameter Expansion).
  • cp -- ... uses -- to say "no more options", so a file called -weird is not mistaken for an option.

The exit code convention: 0 means success, 1 is a general failure, and 2 means "you called me wrongly" (bad usage). Many standard tools, including grep and bash itself, use 2 for usage errors. More in Exit Codes, set -e and Error Handling.

shift: walking through arguments

shift throws away $1 and moves everything down: $2 becomes $1, $3 becomes $2, and $# drops by one. shift 2 removes two. Looping with while (( $# > 0 )) plus shift is the classic way to consume arguments of unknown count.

Bash Consuming arguments with shift

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

shift 2 with fewer than two arguments left fails with status 1 and removes nothing (it prints an error only after shopt -s shift_verbose). If your loop relies on shift making progress, check $# first, or a missing option value will make it loop forever.

Short options with getopts

For options like -v, -n 3 and -o file, Bash has the builtin getopts. You give it a string describing which letters are options and which take a value, and it hands them to you one at a time.

TEXT
getopts "vn:o:" opt
         | |  |
         | |  +-- "o:" : -o takes a value (a colon after the letter)
         | +----- "n:" : -n takes a value
         +------- "v"  : -v is a plain flag
  • The value of the option goes into the variable OPTARG.
  • OPTIND is the index of the next argument to process. After the loop, shift $((OPTIND - 1)) removes all options and leaves only the remaining non-option arguments.
  • A leading colon in the string (":vn:") switches to silent error mode: getopts stays quiet about unknown options and you print your own message. In that mode the variable opt becomes ? for an unknown option (with the letter in OPTARG) and : for a missing value.
Bash getopts with flags, values and leftovers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

What you should take from the output:

  • -vn5 works: getopts understands grouped short flags and a value glued to the letter.
  • Parsing stops at the first non-option word. In the last run, -v after file1 is treated as a plain argument. GNU tools like ls and grep accept options anywhere, but getopts follows the POSIX rule. If you want options anywhere, use the loop in the next section.
  • -- ends option parsing explicitly, so bash opts.sh -- -v treats -v as an argument.

The plain getopts builtin has one big limit: no long options (--verbose). There is also an external program called getopt that supports them, but its behavior differs between systems (GNU getopt versus the old BSD one), so most portable scripts avoid it and write a loop instead.

Long options with a while-case loop

A hand-written loop is simple, handles both --name value and --name=value, and accepts options in any position.

Bash A loop that understands long options

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

The shift at the bottom of the loop consumes the current word. Options that take a separate value do an extra shift inside their branch. The --) branch collects everything left as plain arguments and leaves the loop, so a file really named -v can still be passed. The other forms (collecting non-options into an array, case patterns) are explained in case Statements and Arrays.

Defaults, validation and usage messages

Good scripts decide defaults at the top, validate each value as soon as it is parsed, and print a usage message when asked (-h, --help) or when the call is wrong.

  • Defaults: count=${COUNT:-1} lets an environment variable set the default, an option override it.
  • Validation: check numbers with [[ $n =~ ^[0-9]+$ ]], files with -f, directories with -d. Reject bad values with a message that names the option and the value.
  • Usage text: keep it in a function, written with a here-document, and print it to stdout for --help (the user asked for it) and to stderr after an error.
Bash A usage function and input validation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

The here-document in usage is unquoted (<<USAGE), so ${0##*/} is expanded inside it. See Here-Documents for the rules.

A command-line template

Put the pieces together and you get a skeleton that is worth keeping. It has a main function, a die helper, a usage function, long and short options, validation, and a conventional exit status.

Bash A small CLI template: wordcount with options

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

The flow of the template is always the same:

TEXT
  main "$@"
     |
     +-- loop over args: options set variables, other words go into files[]
     +-- check that required arguments exist       -> exit 2 if not
     +-- apply defaults
     +-- do the real work (functions)               -> exit 1 on runtime failure

When to use what

Need Use
One or two fixed arguments plain $1, $2 with a $# check
Any number of files "$@" in a for loop
A handful of short options getopts
Long options, options in any position, --name=value a while/case/shift loop
Many subcommands, bash completion, rich help consider a real language (Python argparse, Go flag)

When your script wraps another command and should pass unknown options through, collect them into an array (extra+=("$1")) and call othercmd "${extra[@]}". An array keeps spaces intact, a string does not.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A script is called as ./tool.sh "two words" three. What are $# and $1?

    The caller's quotes group the words into a single argument and are removed before the script starts. So there are two arguments, and $1 is the text two words with a space inside.
  2. 2. Which form should you use to pass all your arguments on to another command without breaking those that contain spaces?

    Only "$@" expands to one word per original argument. The other forms either merge everything into one word or split the words again on spaces.
  3. 3. In getopts ":n:v" opt, what does the second colon do, and where is the option's value stored?

    A colon after a letter means that option takes a value, which getopts puts in OPTARG. The first colon (leading) is the one that enables silent error mode.
  4. 4. What does shift $((OPTIND - 1)) do after a getopts loop?

    OPTIND is the index of the next unprocessed argument. Shifting by OPTIND minus 1 drops everything getopts consumed, leaving only the remaining arguments.
  5. 5. Which exit status is the usual convention for "the command was called incorrectly"?

    0 is success and 1 is a general runtime failure. Status 2 signals a usage error, as with grep and bash. 127 means command not found.

Summary

  • Arguments arrive as $1, $2, ... with $# as the count, $0 as the script name and "$@" as the safe list of all of them.
  • Always check $# before using a required argument, send errors to stderr, and exit with 2 for bad usage and 1 for runtime failures.
  • shift drops $1; while (( $# > 0 )) plus shift consumes any number of arguments.
  • getopts parses short options (OPTARG, OPTIND); a leading colon gives you control of error messages. It stops at the first non-option and has no long options.
  • A while/case loop handles long options, --name=value, options in any position, and -- to end option parsing.
  • Validate values early, keep usage in a function, and structure the script around main "$@".

Next: Exit Codes, set -e and Error Handling