Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does while(($#)); do ...; shift; done mean in bash, and why would someone use it?

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?

like image 664
njk2015 Avatar asked Feb 05 '23 22:02

njk2015


1 Answers

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.

like image 132
Benjamin W. Avatar answered Feb 07 '23 11:02

Benjamin W.