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:
| Parameter | Meaning |
|---|---|
$0 | the script's name as it was called |
$1 … $9 | the 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 prodscript: ./args.shcount: 2first: websecond: prodall: web prodQuoting matters here too. Quotes group words into a single argument:
./args.sh "my app" prodscript: ./args.shcount: 2first: my appsecond: prodall: my app prod"$@" 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=10sRunning ./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"$# -lt 2means "fewer than two arguments" (you will learn all the tests in the next lesson).>&2prints to stderr, the error stream, so the message is not mixed into normal output.- Exit code
2is 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 stagingusage: ./deploy.sh APP ENVexit code: 2Deploying checkout to stagingDefaults 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 prodapp=checkout env=stagingapp=payments env=prodThe family of defaults:
| Form | If 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.shregion=us-east-1 replicas=2region=ap-south-1 replicas=4A 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"Useful options:
-rkeeps backslashes as typed. Always use it; without it,\is treated as an escape.-p "text"shows a prompt.-shides the input (for passwords).-t 10gives up after 10 seconds.read -r a b csplits 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"host=web1 ip=10.0.1.10127.0.0.1 localhostA 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"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 web3action: restarttargets: web1 web2 web3 (3 of them)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"doneTyping 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
-ronread: 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$1empty. - Prompting in CI: a
readwith no input hangs or reads nothing. Provide a non-interactive path (FORCE=1,--yes). ${10}written as$10: that is$1followed by0.
Practice
- Write
greet.sh NAME [GREETING]that printsGREETING, NAME!, withHelloas the default greeting. - Make it exit with a usage message on stderr and code 2 when no name is given. Check
$?afterwards. - Write
count.shthat prints how many arguments it got and then each one on its own line usingfor arg in "$@". - Read the first line of
/etc/os-releaseinto a variable withread -rand 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 errorKey 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 -rreads from a person, a pipe or a file; always provide a non-interactive path for automation.