In Bash shell scripting, it’s common to write scripts that call other scripts and need to pass arguments from one script to another. This tutorial will cover how to propagate all arguments in a Bash shell script to another script.
When writing a Bash script, you can access command-line parameters using special variables such as $1
, $2
, etc., where each variable represents a single argument. However, when you need to pass all arguments from one script to another, explicitly specifying each parameter is not practical and can be error-prone.
To solve this problem, Bash provides two special variables: $@
and $*
. Both variables expand to all command-line parameters, but they behave differently when used with quotes.
Unquoted $@
and $*
When used without quotes, both $@
and $*
expand to a single string containing all command-line parameters separated by spaces. This means that if your arguments contain spaces, they will be split into multiple arguments.
For example:
#!/bin/bash
bar $@
In this case, if you run the script with arguments arg1 arg2 "arg3 with space"
, the bar
script will receive four separate arguments: arg1
, arg2
, arg3
, and with space
.
Quoted $@
When used with quotes, $@
expands to a list of individual arguments, where each argument is enclosed in double quotes. This means that arguments containing spaces are preserved as a single argument.
For example:
#!/bin/bash
bar "$@"
In this case, if you run the script with arguments arg1 arg2 "arg3 with space"
, the bar
script will receive three separate arguments: arg1
, arg2
, and "arg3 with space"
.
Quoted $*
When used with quotes, $*
expands to a single string containing all command-line parameters separated by spaces. This means that if your arguments contain spaces, they will be split into multiple arguments.
For example:
#!/bin/bash
bar "$*"
In this case, if you run the script with arguments arg1 arg2 "arg3 with space"
, the bar
script will receive a single argument: "arg1 arg2 arg3 with space"
.
Best Practice
To pass all arguments from one script to another while preserving their original form, use quoted $@
. This ensures that arguments containing spaces are treated as a single argument.
#!/bin/bash
bar "$@"
In summary, when passing arguments between Bash shell scripts, use quoted $@
to preserve the original form of each argument and avoid splitting or joining them incorrectly.
Here’s an example script that demonstrates how to pass arguments using quoted $@
:
#!/bin/bash
# Define a function to print arguments
print_args() {
for arg in "$@"; do
echo "$arg"
done
}
# Call the function with some arguments
print_args "arg1" "arg2" "arg3 with space"
When you run this script, it will output:
arg1
arg2
arg3 with space
As expected, each argument is preserved as a single entity, even if it contains spaces.