When using the shift
built-in, have noted this interesting behavior which I have been unable to find documentation for.
Update: the answer was right in front of me, if shift
is called with a value greater than arguments available in $1 - $x
then it will return with a non zero status - hence the script will halt (since I'm using set -e
)!
Using the script test.sh
, executed using arguments:
./test.sh apple orange banana
apple
orange
banana
banana
red
blue
As expected:
- Three arguments echoed.
- Shift two away.
- One remains as
$1
(banana
).
And then without arguments:
./test.sh
# no output
Arguments $1 - $3
don't exist, so no output or shift but $variable1
and $variable2
are now broken!?!
Why? I'm not sure. Appreciate any comments!
But what this does show, it's safer to check the number of positional arguments available before calling shift
e.g.:
[[ $# -ge 2 ]] && shift 2
Of course @bambam2174 - and to be honest, that answer was right in front of me!!! 🤦♂️
See here http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_09_07.html (which I linked to as well!).
That was my own silly fault 🤕 - thanks for setting me right!