Passing arguments to a bash script is a fundamental skill that every Linux user should know. Whether you are writing a simple or complex script, being able to pass arguments allows your scripts to be more dynamic and versatile.
In this comprehensive guide, we will cover the core concepts and practical examples of passing arguments in bash scripts. By the end, you will have the knowledge to use arguments effectively in your own scripts.
What are Arguments in Bash Scripts?
In programming, arguments (also called parameters) are values that are passed to a function or command when it is called.
For example:
echo "Hello World"
Here "Hello World" is the argument being passed to the echo command.
Similarly, in bash scripts arguments allow you to pass dynamic data to your script, instead of hardcoding values.
Some common examples of arguments used in bash scripts:
- Filenames
- Usernames
- Hostnames
- Date ranges
- Search strings
Being able to pass arguments makes your bash scripts more flexible, reusable and powerful.
Ways to Pass Arguments in Bash
There are several methods available to pass arguments to a bash script:
1. Positional Parameters
The simplest way to access arguments passed to a script is through positional parameters.
Here is an example script called script.sh:
#!/bin/bash
echo "First argument: $1"
echo "Second argument: $2"
echo "All arguments: $@"
When executing this script:
./script.sh arg1 arg2 arg3
The output will be:
First argument: arg1
Second argument: arg2
All arguments: arg1 arg2 arg3
As you can see, the arguments passed when calling the script are available through special variables like $1, $2, $@.
$1refers to the first argument$2refers to the second argument$@refers to all arguments
So positional parameters give you easy access on the order of the arguments passed to a script.
2. Special Variable $
You can find out the number of arguments passed to a script with the special variable $#. Here is an example:
#!/bin/bash
echo "Total arguments: $#"
When running it with 3 arguments:
./myscript.sh arg1 arg2 arg3
It will output:
Total arguments: 3
So $# allows you to easily get the count of arguments passed.
3. Array-like Variables
The positional parameters like $1, $2 also have array-like qualities.
You can access them using index numbers inside curly brackets {}:
#!/bin/bash
echo "First argument: ${1}"
echo "Third argument: ${3}"
When calling the script with 3 arguments:
./myscript.sh arg1 arg2 arg3
It will print:
First argument: arg1
Third argument: arg3
So this syntax allows you to access arguments selectively, by their position index.
4. Special Array Variable $@
The $@ variable allows you to access all arguments as an array. This offers more flexibility than the positional method.
Here is an example script:
#!/bin/bash
arguments=("$@")
echo ${arguments[0]} # First argument
echo ${arguments[1]} # Second argument
echo ${arguments[*]} # All arguments
When passed 3 arguments arg1 arg2 arg3, this script will output:
arg1
arg2
arg1 arg2 arg3
5. Shift Through Arguments with $1
You can easily iterate through arguments by using the shift command, which shifts the argument list and reassigns $1 to the next argument.
For example:
#!/bin/bash
while [[ $# -gt 0 ]]; do
echo "Next argument: $1"
shift
done
This will print each argument on a new line.
So shift gives you an easy way to process arguments in a loop.
Practical Examples of Using Arguments
Now that you understand the main methods of passing args, let‘s go through some practical examples of using them in real scripts.
Example 1: Filename Arguments
A common use case is passing one or more filenames as arguments to a script.
Here is a simple example that prints the filename arguments:
#!/bin/bash
echo "First file: $1"
echo "Second file: $2"
echo "All files: $@"
When running it by passing filenames:
./script.sh file1.txt file2.txt
It will print:
First file: file1.txt
Second file: file2.txt
All files: file1.txt file2.txt
This allows flexible batch processing of multiple files.
Example 2: Count Filename Arguments
Here is a script that counts how many filename arguments were passed:
#!/bin/bash
numArgs=$#
echo $numArgs files passed:
for (( i=1; i<=$#; i++ )); do
echo "File $i: ${!i}"
done
When run with 3 filenames:
./script.sh file1.txt file2.txt file3.txt
Output:
3 files passed:
File 1: file1.txt
File 2: file2.txt
File 3: file3.txt
This shows how $# and indirect parameters help process filenames.
Example 3: Optional Search Argument
If you want to have an optional argument, you can give it a default value if not passed.
Here we pass an optional search phrase argument:
#!/bin/bash
searchTerm=${1:-DefaultSearch}
echo "Search term: $searchTerm"
When running this without an argument:
./script.sh
It will print:
Search term: DefaultSearch
And when passing a search string:
./script.sh "Bash Scripts"
It prints:
Search term: Bash Scripts
So setting a default like ${parameter:-default} allows optional arguments.
Example 4: Argument Validation
A common task is validating arguments passed meet the requirements.
Here is a basic example:
#!/bin/bash
if [[ $1 =~ ^[A-Za-z0-9_]+$ ]]; then
echo "$1 is a valid argument"
else
echo "$1 is not a valid argument" >&2
exit 1
fi
This checks that $1 matches a regex pattern for valid argument strings. If not, it prints an error and exits.
You can validate things like:
- Argument strings match a regex pattern
- Argument is an integer with regex
- Number of arguments passed
This ensures scripts fail fast with invalid arguments.
Example 5: Argument Parsing Options
For more advanced argument handling you can use libraries like Getopts.
Here is an example script:
#!/bin/bash
# Parse options
while getopts ":ab:" option; do
case $option in
a) echo "-a option set">&2;;
b) echo "-b found, arg: $OPTARG";;
\?) echo "Invalid option: -$OPTARG">&2; exit 1;;
esac
done
# Handle remaining arguments
echo "Remaining arguments: $*"
This allows you to handle flags and options like -a or -b value as well as positional arguments.
The benefits of Getopts include:
- Flexible options like
-a,-b value - Automatic error handling
- Distinguishing options/arguments
- Argument validation
For production scripts, using a parser makes argument handling easier.
Tips for Effective Use of Arguments
Here are some best practices for using arguments in your bash scripts:
- Validate required arguments are passed with if checks
- Use clear, logical argument names (e.g. filename not arg1)
- Consider making frequently used args optional
- Print usage help with missing arguments
- Use getopts or other parsing libraries for complex cases
- Access arguments consistently instead of hardcoding values
Following these tips will help other users understand how to use arguments properly when running your script.
Conclusion
Handling arguments is an essential bash scripting skill that allows you to write flexible, modular scripts instead of monolithic ones.
In this guide we covered core concepts like positional parameters, special variables, shift as well as practical examples ranging from simple to more advanced cases.
You now understand methods like:
- Accessing arguments with $1, $2 etc
- Getting total arguments with $#
- Using $@ array-like behavior
- Shifting through args
- Validating and parsing arguments
You also saw practical examples of passing filenames, search strings, options and more.
With this foundation you can start effectively using arguments in your own bash scripts. Your scripts will now be more extensible, reusable across different environments.
So leverage arguments to reduce duplication and unlock the true power of bash scripting!


