Skip to content
$ lynuxpro
← Bash Scripting

LESSON 3 OF 17 · BEGINNER · 16 MIN

Script arguments and user input

HOW IT WORKSGetting input into a script

web → $1Command line./deploy.sh web prod$1 $2 $# "$@"positional
1/4

Words after the script name arrive as $1, $2 and so on. $# is how many there are; "$@" is all of them.

$ ./deploy.sh web prod
$1=web  $2=prod  $#=2

A script that always does exactly the same thing is useful once. A script that accepts input, such as which app to deploy or which environment to target, is useful forever. This lesson covers the three ways input reaches a script: command-line arguments, environment variables and interactive input with read.

In simple words

  • Positional parameters: $1, $2 and so on: the arguments given to the script. $# is how many there are.
  • "$@": all the arguments, each kept as its own word. The safe way to pass them on.
  • Default value: ${var:-default} uses a fallback when the variable is empty or unset.
  • read: asks the user to type something and saves it in a variable.

Positional parameters

Words you type after the script name are called arguments. Inside the script they are available as positional parameters:

ParameterMeaning
$0the script's name as it was called
$1 … $9the first nine arguments
${10}the tenth (braces needed after 9)
$#how many arguments there are
"$@"all arguments, each kept as a separate word
"$*"all arguments joined into one string

Create a script that prints them:

printf '#!/usr/bin/env bash\necho "script: $0"\necho "count:  $#"\necho "first:  $1"\necho "second: $2"\necho "all:    $@"\n' > args.shchmod +x args.sh./args.sh web prod
SHELLbashutf-8 · 3L
script: ./args.shcount:  2first:  websecond: prodall:    web prod
OUTPUTterminalutf-8 · 5L

Quoting matters here too. Quotes group words into a single argument:

./args.sh "my app" prod
SHELLbashutf-8 · 1L
script: ./args.shcount:  2first:  my appsecond: prodall:    my app prod
OUTPUTterminalutf-8 · 5L

"$@" versus $*

When a script passes its arguments on to another command, always use "$@" with the quotes. It forwards each argument exactly as received. $* and unquoted $@ re-split everything on spaces:

#!/usr/bin/env bash# wrapper.sh - add a default flag, pass the rest throughexec kubectl get "$@" --request-timeout=10s
SHELLbashutf-8 · 3L

Running ./wrapper.sh pods -l "app=my api" passes app=my api as one argument. With $* it would arrive as two.

Validating arguments

Good scripts check their input first and fail with a clear message instead of failing halfway through:

#!/usr/bin/env bashif [[ $# -lt 2 ]]; then  echo "usage: $0 APP ENV" >&2  echo "example: $0 checkout staging" >&2  exit 2fiapp=$1env=$2echo "Deploying $app to $env"
SHELLbashutf-8 · 9L
  • $# -lt 2 means "fewer than two arguments" (you will learn all the tests in the next lesson).
  • >&2 prints to stderr, the error stream, so the message is not mixed into normal output.
  • Exit code 2 is the convention for "wrong usage".

Try it:

printf '#!/usr/bin/env bash\nif [[ $# -lt 2 ]]; then\n  echo "usage: $0 APP ENV" >&2\n  exit 2\nfi\necho "Deploying $1 to $2"\n' > deploy.shchmod +x deploy.sh./deploy.sh checkoutecho "exit code: $?"./deploy.sh checkout staging
SHELLbashutf-8 · 5L
usage: ./deploy.sh APP ENVexit code: 2Deploying checkout to staging
OUTPUTterminalutf-8 · 3L

Defaults with ${var:-default}

Often an argument is optional. Parameter expansion gives you defaults in one line:

printf '#!/usr/bin/env bash\napp=${1:-checkout}\nenv=${2:-staging}\necho "app=$app env=$env"\n' > defaults.shchmod +x defaults.sh./defaults.sh./defaults.sh payments prod
SHELLbashutf-8 · 4L
app=checkout env=stagingapp=payments env=prod
OUTPUTterminalutf-8 · 2L

The family of defaults:

FormIf the variable is unset or empty…
${var:-word}use word, leave var alone
${var:=word}use word and assign it to var
${var:?message}print message and exit the script
${var:+word}(reverse) use word only if var is set

${1:?missing app name} is a compact way to make an argument required.

Environment variables as input

CI systems, containers and cron pass settings through the environment. Read them like any variable and give them defaults:

printf '#!/usr/bin/env bash\nregion=${AWS_REGION:-us-east-1}\nreplicas=${REPLICAS:-2}\necho "region=$region replicas=$replicas"\n' > env-input.shchmod +x env-input.sh./env-input.shAWS_REGION=ap-south-1 REPLICAS=4 ./env-input.sh
SHELLbashutf-8 · 4L
region=us-east-1 replicas=2region=ap-south-1 replicas=4
OUTPUTterminalutf-8 · 2L

A common pattern: arguments for what to do, environment for how to do it. ./deploy.sh checkout prod with DRY_RUN=1 in the environment.

Interactive input with read

read waits for a line of input and stores it in a variable:

read -r -p "Which environment? " envecho "You chose $env"
SHELLbashutf-8 · 2L

Useful options:

  • -r keeps backslashes as typed. Always use it; without it, \ is treated as an escape.
  • -p "text" shows a prompt.
  • -s hides the input (for passwords).
  • -t 10 gives up after 10 seconds.
  • read -r a b c splits the line into several variables on spaces.

read also reads from a pipe or a file, which is how scripts process input without a person typing:

echo "web1 10.0.1.10" | { read -r host ip; echo "host=$host ip=$ip"; }read -r first_line < /etc/hostsecho "$first_line"
SHELLbashutf-8 · 3L
host=web1 ip=10.0.1.10127.0.0.1 localhost
OUTPUTterminalutf-8 · 2L

A confirmation prompt

Dangerous scripts should ask before acting, unless they are told it is fine:

#!/usr/bin/env bashenv=${1:?usage: $0 ENV}if [[ $env == prod && ${FORCE:-0} != 1 ]]; then  read -r -p "Really deploy to PROD? [y/N] " answer  [[ $answer == [yY] ]] || { echo "Aborted."; exit 1; }fiecho "Deploying to $env"
SHELLbashutf-8 · 7L

The default answer is No (capital N), so pressing Enter cancels. In CI, where nobody can type, FORCE=1 skips the prompt.

shift: walking through arguments

shift drops $1 and moves every other argument down by one. It is handy when the first argument is a sub-command:

printf '#!/usr/bin/env bash\naction=$1\nshift\necho "action: $action"\necho "targets: $@ ($# of them)"\n' > ctl.shchmod +x ctl.sh./ctl.sh restart web1 web2 web3
SHELLbashutf-8 · 3L
action: restarttargets: web1 web2 web3 (3 of them)
OUTPUTterminalutf-8 · 2L

For real options like -v or -e prod you will use getopts in a later lesson.

Real-world scenario: a safe restart helper

An on-call engineer restarts services on many hosts. Their helper takes the service name as an argument, the host list from an environment variable, and asks before touching production:

#!/usr/bin/env bashservice=${1:?usage: $0 SERVICE}hosts=${HOSTS:-web1 web2}env=${ENVIRONMENT:-staging} echo "Will restart $service on: $hosts ($env)"if [[ $env == prod ]]; then  read -r -p "Type the service name to confirm: " confirm  [[ $confirm == "$service" ]] || { echo "Confirmation failed" >&2; exit 1; }fifor h in $hosts; do  echo "ssh $h sudo systemctl restart $service"done
SHELLbashutf-8 · 13L

Typing the service name to confirm is a deliberate speed bump that has saved many teams from restarting the wrong thing.

Common mistakes

  • Using $* or unquoted $@ when forwarding arguments: values with spaces break.
  • Forgetting -r on read: Windows paths and regexes lose their backslashes.
  • No validation: a missing argument becomes an empty string and the script carries on, for example running rm -rf "/data/$1" with $1 empty.
  • Prompting in CI: a read with no input hangs or reads nothing. Provide a non-interactive path (FORCE=1, --yes).
  • ${10} written as $10: that is $1 followed by 0.

Practice

  1. Write greet.sh NAME [GREETING] that prints GREETING, NAME!, with Hello as the default greeting.
  2. Make it exit with a usage message on stderr and code 2 when no name is given. Check $? afterwards.
  3. Write count.sh that prints how many arguments it got and then each one on its own line using for arg in "$@".
  4. Read the first line of /etc/os-release into a variable with read -r and print it.

Cheat sheet

$0 $1 $2 ${10}          script name and arguments$#                      number of arguments"$@"                    all arguments, safely (use this)shift                   drop $1, move the rest down${1:-default}           default value${1:?message}           required, exit if missing${VAR:-x}               env var with defaultread -r -p "Q? " var    ask a questionread -r a b < file      read first line, split into wordsecho "error" >&2        message to stderrexit 2                  usage error
OUTPUTterminalutf-8 · 11L

Key takeaways

  • Arguments arrive as $1, $2 …; $# counts them and "$@" forwards them safely.
  • Validate input at the top of the script and exit with a usage message on stderr.
  • ${var:-default} and ${var:?message} handle optional and required values in one line.
  • Use environment variables for settings, especially in CI and containers.
  • read -r reads from a person, a pipe or a file; always provide a non-interactive path for automation.