Practical examples of command-line arguments in shell scripts examples
Quick, realistic examples of command-line arguments in shell scripts examples
Let’s start with the kind of script you actually write at 2 a.m. when a deployment breaks. These are small, focused examples of command-line arguments in shell scripts examples that show how to:
- Accept filenames and options
- Provide helpful
--helpoutput - Fail fast when required arguments are missing
Here’s a minimal script that expects exactly one argument: a filename.
#!/usr/bin/env bash
set -euo pipefail
if [ "$#" -ne 1 ]; then
echo "Usage: $0 <file>" >&2
exit 1
fi
file=$1
if [ ! -f "$file" ]; then
echo "Error: '$file' is not a file" >&2
exit 1
fi
wc -l "$file"
This is a tiny example of positional command-line arguments: \(# for the count, \)1 for the first argument. It’s boring, and that’s exactly why it’s reliable.
Best examples of positional arguments in shell scripts
Positional arguments are the first thing most people learn: \(1, \)2, $3, and so on. The best examples are simple utilities that behave like standard Unix tools.
Example: backup script with date and directory
Imagine a backup script used in a cron job on a small server:
#!/usr/bin/env bash
set -euo pipefail
if [ "$#" -lt 2 ]; then
echo "Usage: $0 <source_dir> <backup_dir> [label]" >&2
exit 1
fi
src_dir=$1
backup_dir=$2
label=${3:-manual}
if [ ! -d "$src_dir" ]; then
echo "Error: source directory '$src_dir' not found" >&2
exit 1
fi
mkdir -p "$backup_dir"
timestamp=$(date +%Y%m%d-%H%M%S)
archive="\(backup_dir/backup-}\(label}-${timestamp}.tar.gz"
tar -czf "\(archive" -C "\)src_dir" .
echo "Created backup: $archive"
This is one of the best examples of command-line arguments in shell scripts examples for teaching:
- Required positional arguments: source and destination
- Optional third argument with a default (
label) - Validation with clear error messages
This pattern shows up everywhere in 2024–2025: database dumps, log archiving, even simple data science workflows.
getopts example of short options in shell scripts
After positional arguments, the next step is short options like -v or -f. The standard approach in POSIX shell is getopts. These examples of command-line arguments in shell scripts examples focus on that pattern.
Example: log filtering script with flags
#!/usr/bin/env bash
set -euo pipefail
usage() {
echo "Usage: $0 [-i input_file] [-l level] [-h]" >&2
echo " -i Input log file (default: /var/log/syslog)" >&2
echo " -l Log level to filter (INFO, WARN, ERROR)" >&2
echo " -h Show this help" >&2
}
input_file=/var/log/syslog
level=""
while getopts ":i:l:h" opt; do
case $opt in
i) input_file=$OPTARG ;;
l) level=$OPTARG ;;
h)
usage
exit 0
;;
:)
echo "Option -$OPTARG requires an argument." >&2
usage
exit 1
;;
\?)
echo "Unknown option: -$OPTARG" >&2
usage
exit 1
;;
esac
done
shift $((OPTIND - 1))
if [ -n "$level" ]; then
grep "\(level" "\)input_file"
else
cat "$input_file"
fi
This example of short-option parsing demonstrates:
- Default values for options
- Required option arguments (
-i file,-l level) - A
-hhelp flag
Scripts like this show up in CI logs, container logs, and local debugging workflows.
For a deeper reference on shell behavior, the POSIX Shell Command Language specification from The Open Group is still the gold standard.
Long-option examples of command-line arguments in shell scripts examples
Plain getopts doesn’t support GNU-style long options like --verbose or --config. You can still support them with a small wrapper. These examples include a hybrid approach: -v and --verbose both work.
Example: deployment helper with long options
#!/usr/bin/env bash
set -euo pipefail
usage() {
cat <<EOF
Usage: $0 [options]
Options:
-e, --env ENV Target environment (dev|staging|prod)
-c, --config FILE Config file path
-v, --verbose Enable verbose output
-h, --help Show this help
EOF
}
env="dev"
config=""
verbose=0
## Manual long-option handling
while [ "$#" -gt 0 ]; do
case "$1" in
-e|--env)
env=$2
shift 2
;;
-c|--config)
config=$2
shift 2
;;
-v|--verbose)
verbose=1
shift
;;
-h|--help)
usage
exit 0
;;
--)
shift
break
;;
-*)
echo "Unknown option: $1" >&2
usage
exit 1
;;
*)
# # Positional argument; stop option parsing
break
;;
esac
done
[ -z "\(config" ] && config="config.}\(env}.yaml"
[ "\(verbose" -eq 1 ] && echo "Deploying to '\)env' using config '$config'"
## Simulate deployment
if [ ! -f "$config" ]; then
echo "Error: config file '$config' not found" >&2
exit 1
fi
echo "Deployment completed for environment: $env"
This is one of the more realistic examples of command-line arguments in shell scripts examples used in 2024–2025:
- Works cleanly in CI/CD pipelines
- Plays nicely with tools like Docker, where you often pass
--envor--config - Easy to extend with new flags as your deployment grows
Real examples: mixing options and positional arguments
In real scripts, you rarely have only flags or only positional arguments. You usually have a mix: options to control behavior and positional arguments to specify targets.
Example: image processing wrapper
Suppose you wrap convert (from ImageMagick) with your own defaults:
#!/usr/bin/env bash
set -euo pipefail
usage() {
echo "Usage: $0 [-q quality] [-s size] input_file output_file" >&2
}
quality=85
size="1024x1024"
while getopts ":q:s:h" opt; do
case $opt in
q) quality=$OPTARG ;;
s) size=$OPTARG ;;
h)
usage
exit 0
;;
:)
echo "Option -$OPTARG requires an argument." >&2
usage
exit 1
;;
\?)
echo "Unknown option: -$OPTARG" >&2
usage
exit 1
;;
esac
done
shift $((OPTIND - 1))
if [ "$#" -ne 2 ]; then
usage
exit 1
fi
input=$1
output=$2
convert "\(input" -resize "\)size" -quality "\(quality" "\)output"
echo "Wrote \(output (size=\)size, quality=$quality)"
This pattern shows up a lot in data-processing pipelines. These examples include:
- Options that tweak behavior (
-q,-s) - Required positional arguments at the end (
input_file,output_file)
You can adapt this structure for CSV processing, JSON cleanup, or even simple ETL jobs.
Best examples of safe argument handling in modern shell scripts
Modern shell scripting (especially in production) leans heavily on safety:
set -euo pipefailto fail early- Quoting variables consistently
- Validating user input
These examples of command-line arguments in shell scripts examples show how to avoid the classic foot‑guns.
Example: validating numeric arguments
#!/usr/bin/env bash
set -euo pipefail
if [ "$#" -lt 1 ]; then
echo "Usage: $0 <seconds>" >&2
exit 1
fi
seconds=$1
if ! printf '%s' "\(seconds" | grep -Eq '^[0-9]+\)'; then
echo "Error: seconds must be a non-negative integer" >&2
exit 1
fi
echo "Sleeping for $seconds seconds..."
sleep "$seconds"
This small example of argument validation prevents obvious mistakes like ./wait.sh 10s. When you’re writing scripts that touch production data or system settings, this kind of validation stops bad input from becoming a bad day.
For broader guidance on command-line tool design, the GNU project’s documentation on Command-Line Interfaces is worth reading, even if you’re writing Bash instead of C.
Real examples: argument parsing in CI and data workflows
In 2024–2025, shell scripts are everywhere in CI/CD and data workflows. You see them in GitHub Actions, GitLab CI, Jenkins, and Airflow tasks. A few real examples of command-line arguments in shell scripts examples from those environments:
Example: test runner with environment selection
#!/usr/bin/env bash
set -euo pipefail
usage() {
echo "Usage: $0 [-e env] [-- extra_pytest_args...]" >&2
}
env="dev"
while [ "$#" -gt 0 ]; do
case "$1" in
-e)
env=$2
shift 2
;;
--)
shift
break
;;
-h|--help)
usage
exit 0
;;
*)
echo "Unknown option: $1" >&2
usage
exit 1
;;
esac
done
export APP_ENV="$env"
echo "Running tests in environment: $APP_ENV"
pytest "$@"
This pattern lets CI jobs run ./run_tests.sh -e staging -- -k smoke and forward any remaining arguments to pytest. It’s a neat example of combining your own flags with pass‑through arguments.
Example: data import script with required file and optional date
#!/usr/bin/env bash
set -euo pipefail
usage() {
echo "Usage: $0 -f file.csv [-d YYYY-MM-DD]" >&2
}
file=""
import_date=$(date +%F)
while getopts ":f:d:h" opt; do
case $opt in
f) file=$OPTARG ;;
d) import_date=$OPTARG ;;
h)
usage
exit 0
;;
:)
echo "Option -$OPTARG requires an argument." >&2
usage
exit 1
;;
\?)
echo "Unknown option: -$OPTARG" >&2
usage
exit 1
;;
esac
done
if [ -z "$file" ]; then
echo "Error: -f file.csv is required" >&2
usage
exit 1
fi
if [ ! -f "$file" ]; then
echo "Error: file '$file' not found" >&2
exit 1
fi
echo "Importing \(file for date \)import_date"
## python import_data.py --file "\(file" --date "\)import_date"
Again, these are real examples of command-line arguments in shell scripts examples that show up in production—not toy scripts.
If you’re using shell scripts to trigger scientific or health‑related data pipelines, it’s worth looking at how research institutions structure their tooling. For instance, the National Institutes of Health and Harvard University both publish open-source tooling and data workflows that often rely on small, focused scripts with clear argument handling.
FAQ: examples of command-line arguments in shell scripts examples
What is a simple example of command-line arguments in a shell script?
A very simple example is a script that expects one argument and prints it:
#!/usr/bin/env bash
if [ "$#" -ne 1 ]; then
echo "Usage: $0 <name>" >&2
exit 1
fi
echo "Hello, $1"
You run it as ./greet.sh Alice, and Alice is available as $1.
How do I handle both options and positional arguments together?
Parse options first (with getopts or a manual loop), then run shift \(((OPTIND - 1)) or the appropriate shift calls. Whatever remains in \)@ after shifting are your positional arguments. Many of the best examples above—like the image processing and test runner scripts—use exactly this pattern.
Are there real examples of long options like --config in shell scripts?
Yes. Long options are very common in deployment, backup, and data-import scripts. The deployment helper example above shows -c and --config as aliases. You manually match --config in a case statement and shift two arguments (option plus value). This gives you GNU-style ergonomics without needing extra tools.
Should I always use getopts for argument parsing?
For short options, getopts is usually the right choice because it’s portable and built into the shell. For long options or more complex needs (subcommands, config files, etc.), many teams either:
- Write a small manual parser (as in the long-options example)
- Or move heavier logic into Python, Ruby, or Go and keep the shell script thin
The examples of command-line arguments in shell scripts examples here are designed to cover the 80% use cases where Bash is still a good fit.
Where can I learn more about writing reliable shell scripts?
In addition to the POSIX and GNU references mentioned earlier, look at:
- The Bash manual: https://www.gnu.org/software/bash/manual/bash.html
- Shell style guides from large organizations (Google, GitHub, etc.)
These resources align well with how modern infrastructure and data teams write shell scripts today.
Related Topics
Practical examples of examples of variables in shell scripting
Examples of Regular Expressions in Shell Scripts: 3 Practical Examples You’ll Actually Use
Practical examples of command-line arguments in shell scripts examples
Practical examples of shell script examples for beginners
Practical examples of working with arrays in shell scripting: 3 examples you’ll actually use
Practical examples of string manipulation in shell scripts: 3 examples that actually matter
Explore More Shell Scripting Snippets
Discover more examples and insights in this category.
View All Shell Scripting Snippets