continue and break for loop in Bash is very interesting, I think I did see another have similar syntax, just couldn’t remember which, but my memory could be wrong. Anyway, the syntaxes are:
continue [n] break [n]
The n specifies which loop you want to continue or break. A quick and random and meaningless example:
for i in {a..z}; do for j in {0..9}; do ((j % 3 == 0)) && continue ((j % 7 == 0)) && continue 2 [[ $i == a ]] && break [[ $i == e ]] && break 2 echo $i $j done done
The result is:
b 1 b 2 b 4 b 5 c 1 c 2 c 4 c 5 d 1 d 2 d 4 d 5
So far, I have only used it once even I had known about it for very long time. If I recall correctly, I did dream of this kind of syntax one time when I was coding a double loop in Python and needed to continue the outer loop. As you could imagine, some ugly code would have to be made. By ugly, meaning unwanted variable would have to be created just to check if continue the outer loop.
Bash always has some interesting things laying around. Recently, I learned this is valid syntax from /usr/bin/zgrep:
case "$var" in (abc) : do something ;; esac
The left parenthesis is optional, and it’s a valid POSIX syntax. Surprise.
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.