3

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.

9

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.