Sorter coder

Bash Loops: for loops

tags : bash, level: shu, easy

over
over
over
over
over
bash concept map
for loop
C style
numbers
strings
arrays
associative
arrays
output
of a command

Syntax

for item in <List>
do
  <Commands>
done

# Short style
for item in <List>; do <Commands>; done

Over numbers

Using brace expansion Using seq Output
for i in {1..10}; do echo $i; done for i in $(seq 1 10); do echo $i; done 1 2 3 4 5 6 7 8 9 10
for i in {1..10..2}; do echo $i; done for i in $(seq 1 10 2); do echo $i; done 1 3 5 7 9

More about: brace expansion, seq command

Over strings

for i in a b c d e; do echo "$i"; done

C Style

for (( i=1; i<=10; i++ )); do echo "$i"; done

Over output of a command

for i in $(ls); do echo "File name: $i"; done

Over arrays

for index   in ${!MY_ARRAY[@]}; do echo "$index = ${MY_ARRAY[$index]}"; done
for element in ${MY_ARRAY[@]};  do echo  $element; done

more about arrays

Over associative arrays

for key in ${!MY_ARRAY[@]}; do echo $key; done
for value in ${MY_ARRAY[@]}; do echo $value; done

more about associative arrays