More Bash answers

by Danny
Published 2 min read

Read script arguments with

The short answer

#

Words after the script name arrive as positional parameters. The first is $1, the second $2, and so on. $# is how many there are, and "$@" is all of them, each kept as a separate word.


_10
#!/usr/bin/env bash
_10
echo "Script: $0"
_10
echo "First: $1"
_10
echo "Count: $#"
_10
for arg in "$@"; do
_10
echo "Arg: $arg"
_10
done


_10
./greet.sh alice "bob smith"

Why it happens

#

When you run a script, the shell splits the command line into words, using quotes to decide where each word starts and ends, and passes them to the script. Inside the script they are available as numbered variables:

VariableMeaning
$0the name the script was run as
$1 to $9the first nine arguments
${10}the tenth and later; braces are required
$#the number of arguments
"$@"every argument as a separate word
"$*"every argument joined into one string

The quotes matter. "$@" keeps "bob smith" as one argument. Unquoted $@ or $* splits it into bob and smith, and expands any glob characters. When passing arguments on to another command, "$@" is almost always what you want.

How to fix it

#

Required arguments and defaults

Check the count and print a usage message when something is missing:


_10
if (( $# < 1 )); then
_10
echo "Usage: $0 source [destination]" >&2
_10
exit 1
_10
fi
_10
_10
src=$1
_10
dest=${2:-./backup} # default when the second argument is missing or empty

A shorter way to require an argument is the :? expansion, which stops the script with your message if the value is missing:


_10
src=${1:?Usage: backup.sh source [destination]}

Give positional parameters names early. $src is much easier to follow than $1 twenty lines later.

Loop with shift

shift drops $1 and moves every other argument down one place. That makes it easy to handle a leading option and then treat the rest as a list:


_10
verbose=false
_10
if [[ "$1" == "-v" ]]; then
_10
verbose=true
_10
shift
_10
fi
_10
_10
for file in "$@"; do
_10
$verbose && echo "Processing $file"
_10
wc -l "$file"
_10
done

Parse short flags with getopts

For real options such as -v or -o output.txt, use the built-in getopts. The option string lists each letter; a colon after a letter means it takes a value. A leading colon lets you handle errors yourself.


_22
#!/usr/bin/env bash
_22
usage() {
_22
echo "Usage: $0 [-v] [-o output] file..." >&2
_22
exit 1
_22
}
_22
_22
verbose=false
_22
output="out.txt"
_22
_22
while getopts ":vo:h" opt; do
_22
case $opt in
_22
v) verbose=true ;;
_22
o) output=$OPTARG ;;
_22
h) usage ;;
_22
:) echo "Option -$OPTARG needs a value" >&2; usage ;;
_22
\?) echo "Unknown option -$OPTARG" >&2; usage ;;
_22
esac
_22
done
_22
shift $((OPTIND - 1)) # remove the parsed options
_22
_22
(( $# > 0 )) || usage
_22
echo "Writing $# files to $output"

After the shift, "$@" contains only the remaining arguments. getopts also handles combined flags like -vo out.txt for you.

Long options

getopts only supports single-letter options. For flags like --output, a while loop with case and shift is the usual approach:


_10
while (( $# > 0 )); do
_10
case $1 in
_10
-o|--output) output=$2; shift 2 ;;
_10
-v|--verbose) verbose=true; shift ;;
_10
--) shift; break ;;
_10
-*) echo "Unknown option $1" >&2; exit 1 ;;
_10
*) break ;;
_10
esac
_10
done

Common pitfalls

#
  • Writing $10 and getting the first argument followed by a zero. Use ${10}.
  • Using unquoted $@ or $*, which breaks arguments containing spaces.
  • Forgetting shift $((OPTIND - 1)) after getopts, so the options are still in "$@".
  • Reading $1 when it might be missing under set -u. Use ${1:-} to allow an empty value.
  • Expecting getopts to understand --long options. It does not.
  • Passing arguments with source script.sh. The arguments replace the current shell's positional parameters only for the duration of the sourced file, which is rarely what you intended.
#

Was this resource helpful?