Script Arguments and Options ($@, $#, getopts)
Learn to pass arguments to your scripts and parse command-line options using special variables and 'getopts'.
Script Arguments and Options ($@, $#, getopts) is a free DevOps Bootcamp lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the DevOps Bootcamp learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Script Arguments: Why Use Them?
Ever used a command like ls -l or cp file1 file2? The -l, file1, and file2 are all arguments! They tell the command what to do or what to act upon.
In Bash scripting, arguments make your scripts flexible. Instead of hardcoding values, your script can accept input directly from the command line when it's run.
Accessing Positional Arguments
When you run a script with arguments, Bash automatically assigns them to special variables called positional parameters.
- The first argument is
$1. - The second argument is
$2. - And so on, up to
$9.
For arguments beyond 9, you'd use curly braces like ${10}, ${11}, etc. These variables hold the values passed to your script.
Demo: Positional Arguments
Let's see how to access these arguments in a script. Save this as greet.sh and run it with ./greet.sh Alice Bob.
#!/bin/bash
echo "Hello, $1!"
echo "Welcome, $2."
echo "The third argument (if any) is: $3"`$0` and `$#`: Script Info
Bash provides a few more special variables that give you information about the script itself and its arguments:
$0: This holds the name of the script being executed. It's useful for error messages or logging.$#: This variable contains the total number of positional arguments passed to the script.
These help make your scripts more robust and user-friendly.
Demo: `$0` and `$#`
Run this script with different numbers of arguments, e.g., ./info.sh one two three or just ./info.sh.
#!/bin/bash
echo "Script name: $0"
echo "Number of arguments received: $#"`$@` vs `$*`: All Arguments
Sometimes you need to refer to all the arguments at once. Bash offers two ways:
$@: Expands to separate arguments. When double-quoted ("$@"), each argument remains a distinct word, even if it contains spaces. This is usually preferred for loops.$*: Expands to a single string of all arguments. When double-quoted ("$*"), all arguments are combined into one single word, separated by the first character ofIFS(Internal Field Separator, usually space).
Always use "$@" when iterating through arguments to preserve spaces!
Demo: Looping with `"$@"`
This script demonstrates how "$@" correctly handles arguments with spaces. Run it like: ./loop_args.sh hello "world wide" web
#!/bin/bash
echo "Processing arguments with \"$@\":"
for arg in "$@"; do
echo " Argument: [$arg]"
done
echo "\nProcessing arguments with \"$*\":"
for arg in "$*"; do
echo " Argument: [$arg]"
doneOptions: Beyond Positional Args
Positional arguments are great for simple cases, but what if your script needs optional flags or named parameters, like -v for verbose or -f filename?
This is where command-line options come in. They make scripts more flexible and user-friendly, allowing users to specify settings in any order.
Bash provides the getopts command specifically for parsing these types of options.
`getopts` Syntax: `optstring`
The basic syntax for getopts is: getopts optstring variable.
optstring: A string of valid option characters. If an option requires an argument (like-f filename), follow the character with a colon (e.g.,f:).variable: A variable name wheregetoptswill store the currently processed option character (e.g.,opt).
getopts also sets OPTARG for option arguments and OPTIND for the next argument index.
Demo: Basic `getopts`
This script processes -v (verbose) and -f (file) options. Try running it: ./options.sh -v -f mydata.txt -x or ./options.sh -vf mydata.txt
#!/bin/bash
while getopts "vf:" opt; do
case $opt in
v)
echo "Verbose mode enabled."
;;
f)
echo "File specified: $OPTARG"
;;
\?)
echo "Invalid option: -$OPTARG" >&2
;;
esac
doneQuick Check: Argument Variables
Consider the following script and how it's executed:
#!/bin/bash
echo "Script: $0"
echo "Count: $#"
for arg in "$@"; do
echo "Arg: $arg"
doneIf you run: ./myscript.sh "Hello World" 123
What would be the output?
Recap: Arguments & Options
Great job! You've learned how to make your Bash scripts much more versatile:
- Positional Arguments: Use
$1,$2, etc., to access arguments directly. - Special Variables:
$0for the script name,$#for the argument count, and"$@"to safely iterate through all arguments. - Command-line Options: Use
getoptsto parse named options (like-v) and their arguments (-f filename), making your scripts more robust and user-friendly.
Practice using these in your own scripts to build powerful, flexible command-line tools!
Frequently asked questions
Is the “Script Arguments and Options ($@, $#, getopts)” lesson free?
Yes — the full text of “Script Arguments and Options ($@, $#, getopts)” is free to read here on the web, and the DevOps Bootcamp course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the DevOps Bootcamp course, upgrade to CoddyKit PRO.
What will I learn in “Script Arguments and Options ($@, $#, getopts)”?
Learn to pass arguments to your scripts and parse command-line options using special variables and 'getopts'. You practise DevOps Bootcamp with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start DevOps Bootcamp?
No prior experience is required. DevOps Bootcamp on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Script Arguments and Options ($@, $#, getopts)” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this DevOps Bootcamp lesson?
Yes. Every DevOps Bootcamp lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Looping Constructs (for, while)
- Functions in Bash Scripts
- Script Arguments and Options ($@, $#, getopts)
- The case Statement & Pattern Matching