bash loops | for | while | until

FOR loop

for i in {a..z}; do actions; done;
------------
#!/bin/bash
for i in {a..z};
do
echo $i;
done

--
./sc2
a
...
z
-----
cat sc2
#!/bin/bash
for i in {1..4}
do
echo $i
done

$ ./sc2
1
2
3
4
$
---------------
The for loop can also take the format of the for loop in C.
For example:
for((i=0;i<10;i++)) { commands; # Use $i }

cat sc2
#!/bin/bash
for ((i=0;i<10;i++)){
echo $i
}

------
0
1
......
8
9
---------------------
WHILE

cat sc3
#!/bin/bash
i=0;
while [ $i -lt 9 ]  #SPACE after and before [
do
echo $i
i=$(($i+1))
done

-
./sc3
0..8


Alternative increment

cat sc3
#!/bin/bash
i=0;
while [ $i -lt 9 ]
do let i++
echo $i
done


1....9

----------
most common conditions
-eq’, ‘-ne’, ‘-lt’, ‘-le’, ‘-gt’, or ‘-ge

---------------
UNTIL

 cat until
#!/bin/bash
x=0
until [ $x -eq 9 ]; # [ $x -eq 9 ] is the condition
do let x++
echo $x
done

1....9


Comments

Popular posts from this blog

HAproxy logging

teamcity Automatic Agent Start under Linux

NFS mount add in fstab _netdev instead of default | firewall-cmd --list-all