Bash for loop

Page content

Source

https://linuxize.com/post/bash-for-loop/

for loop

for item in [LIST]
do
  [COMMANDS]
done

loop overstrings

for element in Hydrogen Helium Lithium Beryllium
do
  echo "Element: $element"
done

loop over a number range

for i in {0..3}
do
  echo "Number: $i"
done

loop over number range and increment by 5

for i in {0..20..5}
do
  echo "Number: $i"
done

loop over array elements

BOOKS=('In Search of Lost Time' 'Don Quixote' 'Ulysses' 'The Great Gatsby')

for book in "${BOOKS[@]}"; do
  echo "Book: $book"
done

The C-style Bash for loop

for ((i = 0 ; i <= 1000 ; i++)); do
  echo "Counter: $i"
done

break and continue Statements

for element in Hydrogen Helium Lithium Beryllium; do
  if [[ "$element" == 'Lithium' ]]; then
    break
  fi
  echo "Element: $element"
done

echo 'All Done!'

Output

Element: Hydrogen
Element: Helium
All Done!

continue Statement

for i in {1..5}; do
  if [[ "$i" == '2' ]]; then
    continue
  fi
  echo "Number: $i"
done

until Loop

this script pulls the git host until it’s online/sucessful

#!/bin/bash

until git pull &> /dev/null
do
    echo "Waiting for the git host ..."
    sleep 1
done

echo -e "\nThe git repository is pulled."

Examples

Renaming Files with spaces in the filename

for file in *\ *; do
  mv "$file" "${file// /_}"
done

Changing file extension

for file in *.jpeg; do
    mv -- "$file" "${file%.jpeg}.jpg"
done

sha256: 952f1d11c8934bc1def517fda7ba91d6f59ee4e40f3c5525927a7b6581b46b45