0
0
Bash Scriptingscripting~5 mins

Looping over files and directories in Bash Scripting

Choose your learning style9 modes available
Introduction

Looping over files and directories helps you do the same task on many files automatically. It saves time and avoids mistakes from doing things one by one.

You want to rename all photos in a folder.
You need to check the size of every file in a directory.
You want to convert all text files to another format.
You want to delete all temporary files in a folder.
You want to list all files and do something with each.
Syntax
Bash Scripting
for file in /path/to/directory/*; do
  command "$file"
done

The * means all files and folders inside the directory.

Use quotes around $file to handle names with spaces.

Examples
This prints the full path of every file and folder inside the Documents folder.
Bash Scripting
for file in ~/Documents/*; do
  echo "$file"
done
This shows the content of every text file in the /tmp folder.
Bash Scripting
for file in /tmp/*.txt; do
  cat "$file"
done
This lists only directories inside /var/log by using */ which matches folders.
Bash Scripting
for dir in /var/log/*/; do
  echo "Directory: $dir"
done
Sample Program

This script goes through everything in the current folder. It prints if the item is a file or a directory.

Bash Scripting
#!/bin/bash

# Loop over all files in the current directory
for file in *; do
  if [ -f "$file" ]; then
    echo "File: $file"
  elif [ -d "$file" ]; then
    echo "Directory: $file"
  fi
done
OutputSuccess
Important Notes

Use -f to check if it is a file and -d to check if it is a directory.

Be careful with spaces in file names; always quote variables like "$file".

Using */ matches only directories inside a folder.

Summary

Loops let you repeat commands on many files or folders easily.

Use for with a pattern like * to select files.

Check if an item is a file or directory with -f or -d.