So I am new learning bash script and I came up with the following piece of code.
run_command() {
echo "+" "$@"
"$@"
}
I am confused on what "$@" means and why is it twice?
Thanks a lot for your time and have a great day.
So I am new learning bash script and I came up with the following piece of code.
run_command() {
echo "+" "$@"
"$@"
}
I am confused on what "$@" means and why is it twice?
Thanks a lot for your time and have a great day.
This prints the command and its output.
e.g.
run_command() {
echo "+" "$@"
"$@"
}
run_command ls
#output
#+ ls
#files_list_in_current_directory
Aagam Jain's got the answer. I will add some explanation that wouldn't fit in a comment section. I apologize for the verbosity.
Consider this example.
Showing parameters given to a script
test.sh:
echo "$1"
echo "$2"
Let's run this script and give it 2 parameters.
$> bash test.sh ls -l
Result:
ls
-l
First parameter ls
, represented by $1
, is echo'ed in the first line. Second parameter -l
, represented by $2
, is echo'ed in the second line.
Bash manual - let's see what it says
($@) Expands to the positional parameters, starting from one
See this: https://www.gnu.org/software/bash/manual/bash.html#Special-Parameters
How does that impact our example? Let's change test.sh a bit.
Expanding parameters starting from one
test.sh:
echo "$@"
Let's run it.
$> bash test.sh ls -l
Result:
ls -l
$@
listed both parameters in the same line one after the other. If you had 5 parameters, they'd be printed one after the other.
Let's change test.sh a bit more.
Adding a +
to the echo
test.sh:
echo "+" "$@"
Let's run it.
$> bash test.sh ls -l
Result:
+ ls -l
That means, a +
appeared before both parameters were printed.
Change test.sh a bit more.
Executing all provided parameters
test.sh:
echo "+" "@"
"$@"
Let's run this.
bash test.sh ls -l
Result:
+ ls -l
total 4
-rw-r--r-- 1 eapo users 0 Sep 23 19:38 file1
-rw-r--r-- 1 eapo users 19 Sep 23 19:38 test.sh
Great. As the commenters and Aagam mentioned, the script printed out what it was going to execute (using echo "+" "$@"
) and then executed the command. The "$@" basically is just doing ls -lh
. Terminal just executes it as is.
Let's put a function in the script now.
Adding a function in the script
test.sh:
run_command() {
echo "+" "$@"
"$@"
}
run_command ls -l
Note that we are executing the function in the script itself instead of giving it on the command line
Let's run it.
bash test.sh
Result:
+ ls -l
total 4
-rw-r--r-- 1 eapo users 0 Sep 23 19:38 file1
-rw-r--r-- 1 eapo users 58 Sep 23 19:41 test.sh
Hope the examples walk you through how the script functions.