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_10echo "Script: $0"_10echo "First: $1"_10echo "Count: $#"_10for arg in "$@"; do_10 echo "Arg: $arg"_10done
_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:
| Variable | Meaning |
|---|---|
$0 | the name the script was run as |
$1 to $9 | the 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:
_10if (( $# < 1 )); then_10 echo "Usage: $0 source [destination]" >&2_10 exit 1_10fi_10_10src=$1_10dest=${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:
_10src=${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:
_10verbose=false_10if [[ "$1" == "-v" ]]; then_10 verbose=true_10 shift_10fi_10_10for file in "$@"; do_10 $verbose && echo "Processing $file"_10 wc -l "$file"_10done
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_22usage() {_22 echo "Usage: $0 [-v] [-o output] file..." >&2_22 exit 1_22}_22_22verbose=false_22output="out.txt"_22_22while 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_22done_22shift $((OPTIND - 1)) # remove the parsed options_22_22(( $# > 0 )) || usage_22echo "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:
_10while (( $# > 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_10done
Common pitfalls
#- Writing
$10and getting the first argument followed by a zero. Use${10}. - Using unquoted
$@or$*, which breaks arguments containing spaces. - Forgetting
shift $((OPTIND - 1))aftergetopts, so the options are still in"$@". - Reading
$1when it might be missing underset -u. Use${1:-}to allow an empty value. - Expecting
getoptsto understand--longoptions. 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.
Related reading
#Was this resource helpful?