I came across the following while loop in a bash script tutorial online:
while(($#)) ; do
#...
shift
done
I don't understand the use of the positional parameter cardinality in the while loop. I know what the shift
command does, but does the while statement have some special use in conjunction with shift
?
Every time you do shift
, the number of positional parameters is reduced by one:
$ set -- 1 2 3
$ echo $#
3
$ shift
$ echo $#
2
So this loop is executed until every positional parameter has been processed; (($#))
is true if there is at least one positional parameter.
A use case for doing this is (complex) option parsing where you might have options with an argument (think command -f filename
): the argument to the option would be processed and removed with an additional shift
.
For examples of complex option parsing, see BashFAQ/035 and ComplexOptionParsing. The last example of the second link, Rearranging arguments, uses the exact while (($#))
technique.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With