Please consider the script foo.bash
#!/bin/env bash
echo "$@"
echo
for x in "${@:0:$# + 1}" ; do
echo "$x"
done
Then ./foo.bash a b c
gives the output
a b c
./foo.bash
a
b
c
As far as I understand the documentation, @
holds the positional arguments, so the output of echo "$@"
makes sense to me.
But why does the for
loop print the script name?
edit:
I'm using Git BASH on Windows, echo $BASH_VERSION
yields 4.4.23(1)-release
This behavior is specific to bash
ver 4+.
As per man bash
@
Expands to the positional parameters, starting from one. That is,"$@"
is equivalent to"$1" "$2" "$3"
...
However:
${parameter:offset:length}
Substring Expansion. Expands to up to length characters of the value of parameter starting at the character specified by offset. If parameter is@
, an indexed array subscripted by@
or*
, or an associative array name, the results differ as described below. If length is omitted, expands to the substring of the value of parameter starting at the character specified by offset and extending to the end of the value. length and offset are arithmetic expressions (see ARITHMETIC EVALUATION below). If parameter is@
, the result islength
positional parameters beginning atoffset
. If parameter is an indexed array name subscripted by@
or*
, the result is the length members of the array beginning with${parameter[offset]}
.
Substring indexing is zero-based unless the positional parameters are used, in which case the indexing starts at 1 by default. If
offset
is 0, and the positional parameters are used,$0
is prefixed to the list.
So if you use:
"${@:0}"
That will also include $0
however as mentioned earlier:
"$@"
will start from position one.
PS: Note that in previous bash
versions, behavior is different and "${@:0}"
won't include $0
.