mercredi 16 décembre 2015

In shell script, how did 'if-else' in a for loop executed? Why did it only print once for a variable?

I wrote a shell snippet shown as below:

is_first=t
for f in "$path"/"m*"
do
    printf "%s\n" $f
    printf "%s\n" $is_first

    if [[ "$is_first" = "t" ]]; then
        is_first=f
        printf "%s\n" $is_first
    else
        printf "%s\n" $is_first
    fi

    printf "%s\n" $is_first
done

The output is as follows:

./merge_non-null
./merge_non-null_bak.sh
./merge_non-null.sh
t
f
f

I'm wondering, how did if-else execute in a for loop? It seems it runs only for the first loop, and all skipped afterwards.

Also, why does printf "%s\n" $is_first only executed for for the first loop? The output I expected is (note the sequence). I believe I've missed something. Sorry if it's too stupid.

./merge_non-null
t
f
f
./merge_non-null_bak.sh
f
f
f
./merge_non-null.sh
f
f
f

Aucun commentaire:

Enregistrer un commentaire