Ben Chuanlong Du's Blog

It is never too late to learn.

Loops in Bash

Tips and Traps

  1. Forggeting $ is a common mistake when using a shell variable.
In [2]:
%%bash

for x in 1 2 3 4 5; do
	echo $x
done
1
2
3
4
5

In [5]:
%%bash

for x in {1..5}; do
	echo $x
done
1
2
3
4
5

In [6]:
%%bash

for x in {1..5..2}; do
	echo $x
done
1
3
5

In [9]:
%%bash

for x in $(seq 1 2 5); do
    echo $x
done
1
3
5

In [11]:
%%bash

for (( i=1; i<=5; i++ )); do  
   echo $i
done
1
2
3
4
5

In [12]:
%%bash

for (( i=1; i<=5; ++i )); do  
   echo $i
done
1
2
3
4
5

Below is an infinite loop.

In [12]:
%%bash

for (( ; ; )); do  
   echo "This is a infinite loop!"
done
1
2
3
4
5

In [4]:
%%bash

for dir in $(ls -d */); do
    echo $dir
done
f2.csv/
spark-warehouse/

break and continue

break, continue and exit work as in other programming languages.

In [ ]:

Comments