I'm looking at a bash script with the following code:
#!/bin/sh
set -e # Exit if any command fails
# If multiple args given run this script once for each arg
test $2 && {
for arg in $@
do $0 $arg
done
exit
}
.
.
.
As mentioned in the comment the purpose is to "run the script on each argument if there is more than one" I've some runner code to test this out:
# install-unit
# If multiple args given run this script once for each arg
test $2 && {
echo "\$0: $0"
echo "\$1: $1"
echo "\$2: $2"
echo "test \$2 && is true"
}
test $2 && {
# note this is just a regular bash for loop
# http://goo.gl/ZHpBvT
for arg in $@
do $0 $arg
done
exit
}
echo "running: $1"
which gives the following:
sh ❯ ./multiple-run.sh cats and dogs and stuff
$0: ./multiple-run.sh
$1: cats
$2: and
test $2 && is true
running: cats
running: and
running: dogs
running: and
running: stuff
sh ❯ ./multiple-run.sh cats
running: cats
I'd like for someone to unpack the test $2 && {}
part and the exit
shell built in. In the beginning I was thinking that the test $2
was checking to see if there are more args, and maybe it is, but it looks weird because it seems like there's two expressions separated by the "and" &&
, and I'm also just confused what the heck the exit
builtin does.
Plain english explanations with examples and documentation references are appreciated :)
Thanks!
Edit: Thanks Stéphane Chazelas for that. For anyone who is confused by the change in for loop syntax, check out number 3 in this geekstuff article. To summarize:
echo "positional parameters"
for arg do
echo "$arg"
done
echo "\nin keyword"
for arg in "$@"
do echo "$arg"
done
gives us:
❯ ./for-loop-positional.sh cats and dogs
positional parameters
cats
and
dogs
in keyword
cats
and
dogs
for arg do
syntax.