The problem of parameter shift of $1 in the case of Shell for loop

see the following code in shell scripting cookbook

test.sh

-sharp!/bin/bash

if [ $-sharp -ne 3 ]; then
    echo "Usage: $0 URL -d DIRECTORY"
    exit -1
fi

for i in {1..4}; do
    case $1 in
      -d)
        shift
        directory=$1
        shift
        ;;
      *)
        url=${url:-$1}
        shift
        ;;
    esac
done

execute script

-sharp ./test.sh A -d B

in this case, $1 is A $2 is-d $3 is B
Why, after the for statement, why does the $1 judged by case match on-d and enter the branch of-d)? Shouldn"t it be A?
seems to be the $2 parameter moved to $1 after the for statement.

if I for in. If you comment out the two lines of done, you will not enter the-d branch of case.

Why is this happening?

Mar.23,2021

because you use shift

the first loop: there is no match to-d, so it matches *, and there is a shift, in it, so at this time $1 has become-d
the second loop: $1 is already-d, so the logic of-d is executed

Menu