9

When I use the bash shift command, does that change the argument count in $#?

Note from author: When I had this question I did not find it (yet) on this community. Therefore I simply tried it and got my answer. Because I thought it might help others I posted what I learned here as a self-answered question.

0

1 Answer 1

15

Yes is does, it's explicitly required in the standard:

shift [n] The positional parameters shall be shifted. Positional parameter 1 shall be assigned the value of parameter (1+n), [...] and the parameter '#' is updated to reflect the new number of positional parameters.

Consider this script:

#!/usr/bin/env bash
echo "$#"
shift
echo "$#"

Calling it like script-file first second third will print 3 followed by 2.

This means we can do things like:

#!/usr/bin/env bash
while [[ "$#" > 0 ]] ; do
    echo "$1"
    shift
done

...which would print the arguments one by one on their own line.

2

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .