Skip to content

Arguments

Command line arguments allow scripts to accept input from users at runtime. This chapter covers positional parameters, flags, options, and best practices for parsing command-line arguments in bash scripts.


args_basic.sh
#!/usr/bin/env bash
# Access arguments
echo "Script: $0"
echo "First: $1"
echo "Second: $2"
echo "Third: $3"
echo "All: $@"
echo "Count: $#"
args_all.sh
#!/usr/bin/env bash
# $@ - all arguments as separate
for arg in "$@"; do
echo "Arg: $arg"
done
# $* - all arguments as single string
echo "All: $*"

parse_args.sh
#!/usr/bin/env bash
VERBOSE=false
FORCE=false
OUTPUT=""
while [ $# -gt 0 ]; do
case "$1" in
-v|--verbose)
VERBOSE=true
shift
;;
-f|--force)
FORCE=true
shift
;;
-o|--output)
OUTPUT="$2"
shift 2
;;
-h|--help)
echo "Usage: $0 [OPTIONS]"
exit 0
;;
*)
echo "Unknown: $1"
shift
;;
esac
done
echo "Verbose: $VERBOSE"
echo "Force: $FORCE"
echo "Output: $OUTPUT"

deploy.sh
#!/usr/bin/env bash
set -euo pipefail
ENVIRONMENT=""
VERSION="latest"
DRY_RUN=false
show_help() {
cat << EOF
Usage: $0 [OPTIONS] ENVIRONMENT VERSION
Arguments:
ENVIRONMENT Target environment (staging, production)
VERSION Application version
Options:
-h, --help Show this help
-d, --dry-run Dry run mode
EOF
}
while [[ $# -gt 0 ]]; do
case $1 in
-h|--help)
show_help
exit 0
;;
-d|--dry-run)
DRY_RUN=true
shift
;;
-*)
echo "Unknown option: $1"
exit 1
;;
*)
if [ -z "$ENVIRONMENT" ]; then
ENVIRONMENT="$1"
elif [ "$VERSION" = "latest" ]; then
VERSION="$1"
fi
shift
;;
esac
done
if [ -z "$ENVIRONMENT" ] || [ "$VERSION" = "latest" ]; then
show_help
exit 1
fi
echo "Deploying $VERSION to $ENVIRONMENT (dry-run: $DRY_RUN)"
getopts_example.sh
#!/usr/bin/env bash
# Using getopts for option parsing
while getopts "vhf:o:" opt; do
case $opt in
v) VERBOSE=true ;;
h) echo "Help"; exit 0 ;;
f) FILE="$OPTARG" ;;
o) OUTPUT="$OPTARG" ;;
\?) exit 1 ;;
esac
done
shift $((OPTIND -1))
echo "Verbose: ${VERBOSE:-false}"
echo "File: ${FILE:-none}"
echo "Output: ${OUTPUT:-none}"
echo "Remaining: $@"

In this chapter, you learned about:

  • ✅ Positional parameters
  • ✅ $@ vs $*
  • ✅ Argument parsing with while loop
  • ✅ getopts for option parsing
  • ✅ Help message creation
  • ✅ Practical examples

  1. Create script that prints all arguments
  2. Parse simple flags
  1. Create deployment script with argument parsing
  2. Implement help message
  1. Build complete CLI with getopts
  2. Add argument validation

Continue to the next chapter to learn about file operations.


Previous Chapter: Scope and Variable Visibility Next Chapter: File Operations