Resources Infrastructure

Bash Arguments: How to Pass and Read Command Line Arguments in a Bash Script

How a bash script reads command line arguments: positional parameters, the special parameters $#, $@ and $*, default and required values, getopts for short flags, a loop for long named options, and how to pass typed inputs to a bash script from a Kestra flow.

TL;DR — To pass arguments to a bash script, list them after the script name: ./deploy.sh staging 3. Inside the script, $1 is the first argument, $2 the second, ${10} the tenth. $# holds the number of arguments and "$@" all of them. Use ${1:-default} for optional values, getopts for flags like -v or -f file, and a while/case loop for named --long options.

Bash arguments let the same script run in more than one place: one cleanup.sh for staging and production, for 7 days or 30. This page covers how bash reads command line arguments, how to validate them before the script does anything, how to add a help option and flags, and how arguments work inside functions, with examples you can paste into a terminal.

How to pass arguments to a bash script

Bash arguments go after the script name, separated by spaces, and the script reads them as $1, $2, and so on:

./backup.sh production /var/data

Bash splits the command line into words and assigns them to positional parameters. $0 holds the script name as it was called, $1 the first argument, $2 the second:

#!/usr/bin/env bash
echo "Script: $0" # ./backup.sh
echo "Environment: $1" # production
echo "Path: $2" # /var/data

Two rules prevent most argument bugs:

  • Quote arguments that contain spaces when calling the script: ./backup.sh production "/var/app data". Without quotes, /var/app becomes $2 and data becomes $3.
  • Quote parameters when using them inside the script: cp "$2" /backup/, not cp $2 /backup/. An unquoted $2 is split again on spaces.

From the tenth argument on, use braces: ${10}, ${11}. Bash reads $10 as $1 followed by the character 0, without any error.

Special parameters: $#, $@, $* and $0

ParameterContainsTypical use
$0The script name as calledUsage messages
$1 … $9, ${10}One argument eachReading a specific argument
$#The number of argumentsChecking that the required arguments are there
"$@"All arguments, one word eachLooping, forwarding to another command
"$*"All arguments joined into one stringLog lines
$?Exit status of the last commandError handling

The difference between "$@" and "$*" shows as soon as an argument contains a space:

#!/usr/bin/env bash
# ./process.sh "file one.txt" "file two.txt"
for f in "$*"; do echo "[$f]"; done
# [file one.txt file two.txt]
for f in "$@"; do echo "[$f]"; done
# [file one.txt]
# [file two.txt]

Use "$@", with the quotes, whenever the script loops over its arguments or passes all arguments on to another command, for example exec python app.py "$@".

Check the number of arguments

Validate inputs before the script changes anything. $# gives the number of arguments; -z tests that a string is empty:

#!/usr/bin/env bash
if [ "$#" -lt 2 ]; then
echo "Usage: $0 <environment> <bucket>" >&2
exit 1
fi
if [ -z "$1" ]; then
echo "Environment cannot be empty" >&2
exit 1
fi

Error messages go to stderr (>&2) and the script exits with a non-zero status, so whatever calls it, a terminal, cron, or an orchestrator, can tell the run failed.

Default values and required arguments

Parameter expansion handles optional and mandatory arguments in one line each:

#!/usr/bin/env bash
env_name="${1:-staging}" # default when $1 is empty or unset
retries="${2:-3}"
input_file="${3:?missing argument 3: input file}" # stop with this message if missing
echo "Deploying $input_file to $env_name with $retries retries"

${1:=staging}, which assigns the default, does not work on positional parameters: bash stops with $1: cannot assign in this way. Assign the default to a named variable instead, as above.

Validate the type too when the value is used as a number:

[[ "$retries" =~ ^[0-9]+$ ]] || { echo "retries must be a number" >&2; exit 1; }

Loop over arguments with shift

shift drops $1 and moves every other argument down by one, decreasing $#. It fits scripts that take an action followed by a list:

#!/usr/bin/env bash
# ./manage.sh restart api worker scheduler
action="$1"
shift
for service in "$@"; do
echo "$action $service"
done

shift 2 drops two arguments at once.

Ready to orchestrate your infrastructure?

Parse flags with getopts

Once a script has optional settings, flags are easier to use than positions. getopts is a bash builtin that parses short options such as -v or -d 30, including grouped flags like -vn:

#!/usr/bin/env bash
set -euo pipefail
usage() { echo "Usage: $0 -e <environment> [-d <days>] [-n] <directory>..." >&2; exit 2; }
env_name=""
days=7
dry_run=false
while getopts ":e:d:n" opt; do
case "$opt" in
e) env_name="$OPTARG" ;;
d) days="$OPTARG" ;;
n) dry_run=true ;;
:) echo "Option -$OPTARG needs a value" >&2; usage ;;
\?) echo "Unknown option -$OPTARG" >&2; usage ;;
esac
done
shift $((OPTIND - 1)) # "$@" now holds the arguments after the flags
[ -n "$env_name" ] || usage
[ "$#" -ge 1 ] || usage

How the option string ":e:d:n" reads:

  • A letter followed by a colon (e:, d:) takes a value, which getopts stores in $OPTARG.
  • A letter without a colon (n) is a boolean flag.
  • The leading colon turns off the default error messages so the script prints its own: : for a missing value, \? for an unknown option.

After the loop, $OPTIND points to the first argument that is not an option, so shift $((OPTIND - 1)) leaves only the remaining arguments in "$@".

Add a -h help option

A script that takes flags should explain them. Add h to the option string and print the usage line, to stdout and with exit code 0 since the user asked for it:

while getopts ":e:d:nh" opt; do
case "$opt" in
h) echo "Usage: $0 -e <environment> [-d <days>] [-n] <directory>..."; exit 0 ;;
# ... other options as above
esac
done

Calling usage from the : and \? branches, as in the script above, shows the same text when someone passes a wrong option.

Named arguments and long options

getopts does not handle long options such as --env production. The portable way is a while loop over "$@" with a case per option:

#!/usr/bin/env bash
env_name="staging"
verbose=false
while [ "$#" -gt 0 ]; do
case "$1" in
--env)
[ "$#" -ge 2 ] || { echo "--env needs a value" >&2; exit 2; }
env_name="$2"; shift 2 ;;
--env=*) env_name="${1#*=}"; shift ;;
-v|--verbose) verbose=true; shift ;;
--) shift; break ;;
-*) echo "Unknown option: $1" >&2; exit 2 ;;
*) break ;;
esac
done
echo "env=$env_name verbose=$verbose remaining: $*"

This accepts both --env production and --env=production, and stops at -- or at the first argument that is not an option. When --env is the last argument, shift 2 fails without shifting anything, so without the [ "$#" -ge 2 ] check the loop would match --env forever. The external getopt command (without the s) also parses long options, but its behavior differs between Linux and macOS, so scripts meant to run on both usually parse by hand.

Arguments inside bash functions

Inside a function, $1, $2, $# and "$@" refer to the arguments of the function call, not to the script’s arguments. To use the script’s arguments in a function, pass them explicitly:

#!/usr/bin/env bash
greet() {
echo "Hello, $1 ($# argument(s) received)"
}
greet "$1" # pass one script argument
greet "$@" # pass all script arguments

Calling greet with no arguments leaves $1 empty inside the function, even when the script itself received arguments.

Pass arguments to a bash script from Kestra

When a bash script runs on a schedule or from a pipeline, its arguments come from somewhere: a crontab line, a CI variable, a person typing them. In Kestra, they come from flow inputs. The flow below runs the getopts script above on a schedule or on demand, and builds its command line from typed inputs:

id: bash_script_arguments
namespace: company.team
inputs:
- id: environment
type: SELECT
values:
- staging
- production
defaults: staging
- id: retention_days
type: INT
defaults: 7
- id: dry_run
type: BOOL
defaults: true
tasks:
- id: cleanup
type: io.kestra.plugin.scripts.shell.Commands
taskRunner:
type: io.kestra.plugin.scripts.runner.docker.Docker
containerImage: ubuntu:24.04
inputFiles:
cleanup.sh: |
#!/usr/bin/env bash
set -euo pipefail
usage() { echo "Usage: $0 -e <environment> [-d <days>] [-n] <directory>..." >&2; exit 2; }
env_name=""
days=7
dry_run=false
while getopts ":e:d:n" opt; do
case "$opt" in
e) env_name="$OPTARG" ;;
d) days="$OPTARG" ;;
n) dry_run=true ;;
:) echo "Option -$OPTARG needs a value" >&2; usage ;;
\?) echo "Unknown option -$OPTARG" >&2; usage ;;
esac
done
shift $((OPTIND - 1))
[ -n "$env_name" ] || usage
[ "$#" -ge 1 ] || usage
matched=0
for dir in "$@"; do
count=$(find "$dir" -type f -mtime +"$days" | wc -l)
matched=$((matched + count))
if [ "$dry_run" = false ]; then
find "$dir" -type f -mtime +"$days" -delete
fi
done
echo "[$env_name] $matched file(s) older than $days days (dry run: $dry_run)"
echo "::{\"outputs\":{\"files_matched\":$matched}}::"
commands:
- >-
bash cleanup.sh -e "{{ inputs.environment }}" -d {{ inputs.retention_days }}
{{ inputs.dry_run ? '-n' : '' }} .
triggers:
- id: nightly
type: io.kestra.plugin.core.trigger.Schedule
cron: "0 3 * * *"
inputs:
dry_run: false

What this changes compared with a crontab line:

  • Inputs are checked before the script starts. environment only accepts staging or production and retention_days must be an integer, so a typo is rejected at launch instead of reaching find -delete. See flow inputs.
  • The boolean input becomes a flag. {{ inputs.dry_run ? '-n' : '' }} adds -n only when dry_run is true; the script itself stays a plain bash script you can still run by hand. A manual run is a dry run by default, and the nightly trigger passes dry_run: false so the scheduled run deletes files.
  • The result is reusable. The ::{"outputs": ...}:: line makes files_matched available to later tasks, for example to alert when nothing was cleaned up for a week. See outputs from scripts.

The Shell Commands task runs the script in a container here; for scripts that must run on a specific server, see SSH scripts.

Terraform, Ansible and Kubernetes, orchestrated from one place.

Frequently asked questions

Find answers to your questions right here, and don't hesitate to Contact Us if you couldn't find what you're looking for.