Loops in Bash
Posted on Dec 03, 2019 in Computer Science
Things under legendu.net/outdated are outdated technologies that the author does not plan to update any more. Please look for better alternatives.
Fish Shell is preferred to Bash/Zsh. The following content is for Bash/Zsh only.
Tips and Traps¶
- 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
In [5]:
%%bash
for x in {1..5}; do
echo $x
done
In [6]:
%%bash
for x in {1..5..2}; do
echo $x
done
In [9]:
%%bash
for x in $(seq 1 2 5); do
echo $x
done
In [11]:
%%bash
for (( i=1; i<=5; i++ )); do
echo $i
done
In [12]:
%%bash
for (( i=1; i<=5; ++i )); do
echo $i
done
Below is an infinite loop.
In [12]:
%%bash
for (( ; ; )); do
echo "This is a infinite loop!"
done
In [4]:
%%bash
for dir in $(ls -d */); do
echo $dir
done
break and continue¶
break, continue and exit work as in other programming languages.
In [ ]: