Bash File Loops

Some examples of iterating through files and looping through file content in Bash. For details, see the Bash man page or the Bash reference manual.

Loop Through Files

for FILE in *; do
  # do something with $FILE
  echo "File: $FILE"
done

For more control, use /usr/bin/file

for FILE in $(find ./ -name *.html -type f); do
  # do something with $FILE
  echo "HTML File: $FILE"
done

Loop Through Lines in a File

while read LINE; do
  # do something with $LINE
  echo "Line: $LINE"
done < /etc/hosts

Loop Through Words in a File

for WORD in $(cat /etc/hosts); do
  # do something with $WORD
  echo "Word: $WORD"
done

Loop Through Characters in a File

while read -n1 CHAR; do
  # do something with $CHAR
  echo "Character: $CHAR"
done < /etc/hosts

Comments

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

If you have files or

If you have files or directories that have spaces in them, one way to loop over them is with read:

ls * | while read X; do echo cp -p $X ${X}.bak; done

Cheers,
Jeff McCune

That is a very useful hint,

That is a very useful hint, Jeff. Thank you for it!
Peter