Usage of β€œfor” Loop in Bash Directory [5 Examples]

LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now

A Bash directory contains a list of files and subfolders. This directory tree can be used to keep the same types of files in the same directory so that files and directories can be found easily. Sometimes, you might need to search for directories of specific patterns, test the file’s existence, or test whether a file is regular. These tasks can easily be achieved if users loop through files of that bash directory by using a simple for loop. In this article, I will explore the different usages of the for loop in the Bash directory.

5 Examples of Using β€œfor” Loop in Bash Directory

The for loop in the Bash directory enables users to loop through files of multiple directories and do operations like renaming files or moving tons of files to a different directory within a second, counting lines of text files, and testing various conditions of a file. In this section, I will demonstrate a few examples of using the for loop in the Bash directory.

1. Pattern Matching Directories Only

The glob (*/) pattern can easily find directories. If a for loop iterates over */, it will only iterate through the directories of the current directories. Then, the echo command can easily print each iteration entity one by one on the terminal. It is one of the minimalistic approaches to search for directories.

Here is a bash script on how to pattern-match directories:

#!/bin/bash

for directory in */; do
Β Β Β  echo "$directory"
done
EXPLANATION

Here for directory in */; do initiates a for loop that iterates over each entity of the current directory that ends with a */, a glob pattern indicating directories. After that, the echo command has printed the directory names on the terminal.

All directories have been printed on the terminal.The for loop has printed all directories’ names on the terminal.

Warning: Sometimes filenames might contain a slash / at the end. In such cases, a double-check is necessary.

2. Using the Directory File Test Operator

The file test operator performs tests on files and directories and returns a Boolean value that is true or false based on the test result. These operators are often used within conditional statements to make decisions in scripts. Some common file test operators are:

Operator Function
-e Returns true if β€˜file’ exists
-f Returns true if β€˜file’ is a regular file.
-d Returns true if the β€˜file’ is a directory.
-x Returns true if the β€˜file’ is executable.

Here is a practical bash script for testing whether an entity is a directory:

#!/bin/bash

for file_name in *; do
Β Β Β  if [[ -d "$file_name" ]]; then
Β Β Β Β Β Β Β  echo "$file_name"
Β Β Β  fi
done
EXPLANATION

The for file_name in *; do initiate a β€˜for’ loop that iterates over each entity in the current directory. After that if [ -d "$file_name" ]; then checks whether the current entity is a directory with the -d flag. If the existing entity is a directory, the echo command will print its name on the terminal.

All files that are directory has been printed on the terminal.The bash script has printed all directories on the terminal.

3. Renaming Files in a Directory

The filename contains the intention of the file contents. It will change its initial intention if its content is updated, edited, or manipulated. In such cases, file renaming is necessary. Multiple files can be renamed easily with the help of the for loop and the mv command.

Here is the bash script to rename files in a directory:

#!/bin/bash

directory="/home/susmit/directory"
echo "before rename the contents of "/home/susmit/directory" "
ls $directory
if [ -d "$directory" ]; then
Β Β Β  Β Β Β Β Β Β Β  counter=1
Β Β Β  Β Β Β Β Β Β Β  for file in "$directory"/*; do
Β Β Β  Β Β Β Β Β Β Β Β     if [ -f "$file" ]; then
Β Β Β Β Β Β Β Β Β Β Β          #Renaming
Β Β Β Β Β Β Β Β Β Β Β          new_name="newfile_$counter.txt"
Β Β Β Β Β Β Β Β Β Β Β          mv "$file" "$directory/$new_name"
Β Β Β Β Β Β Β Β Β Β Β          echo "Renamed: $file to $new_name"
Β Β Β Β Β Β Β Β Β Β Β          ((counter++))
Β Β Β  Β Β Β Β Β Β Β      fi
Β Β Β  Β Β Β Β Β Β Β  done
else
Β Β Β  Β Β Β Β Β Β Β  echo "Directory does not exist: $directory"
fi

EXPLANATION

At first, directory_path="/home/susmit/directory" assigns a specific directory to the directory_path variable. Then, the present content of the "/home/susmit/directory" will be printed on the terminal. After that, the if [ -d "$directory" ]; then checks if the directory specified by the variable directory exists.

Afterwards, for file in "$directory"/*; do iterates through each file of the current directory. And if [ -f "$file" ]; then checks if the current iteration entity is a regular file.

Then the new_name="newfile_$counter.txt" generates a new name, setting newfile as prefix and counter value as a suffix. After that, the mv "$file" "$directory/$new_name" renames the file by moving it to the same directory with the new name. Then ((counter++)) increments the value of the counter variable.

The for loop has renamed two files.The bash script has changed the name of two files.

4. Counting Lines in All Text Files

File line numbers determine the length of a file. It helps Bash programmers keep the file length concise, a prerequisite for low file size. To monitor the size of files, checking line number files is one of the best practices.

Here is a bash script to count the line number of multiple files:

#!/bin/bash

directory="/home/susmit/directory"

if [ -d "$directory" ]; then
Β Β Β  for file in "$directory"/*.txt; do
Β Β Β Β Β Β Β  if [ -f "$file" ]; then
Β Β Β Β Β Β Β Β Β Β Β  #Count the number of lines in each text file
Β Β Β Β Β Β Β Β Β Β Β  line_count=$(wc -l < "$file")
Β Β Β Β Β Β Β Β Β Β Β  echo "File: $file, Lines: $line_count"
Β Β Β Β Β Β Β  fi
Β Β Β  done
else
Β Β Β  echo "Directory does not exist: $directory"
fi
EXPLANATION

At first, directory="/home/susmit/directory" defines a value of the directory variable. Then if [ -d "$directory" ]; then checks if the directory specified by the variable β€˜directory’ exists.

Afterward, for file in "$directory"/*.txt; do iterates over each file with a β€˜.txt’ extension in the specified directory. And if [ -f "$file" ]; then checks if the current iteration entity is a regular file. Then file will be redirected to the wc -l command, which will count the line number of the file and store it in the line_count variable.

After that, the echo "File: $file, Lines: $line_count" will print the file name and the number of lines in the file on the terminal.

Total line number of two files have been printed individually.

Upon execution, the script prints the file name and the number of lines in the file on the terminal.

Warning: Set the permission properly so that users can access the files and directories.

5. Moving Multiple Files to a Different Directory

The files are located on the system based on the file type and intention. If any file is edited or manipulated, it might change its intention or type. In such cases, the relocation of that file is necessary. Utilizing the mv command with a for loop to move multiple files from one directory to a different directory is one of the most efficient approaches.

Here is the bash script to count the line number of a file:

#!/bin/bash

source_directory=”/home/susmit/directory”
destination_directory=”/home/susmit/destination”

ls /home/susmit/directory
ls /home/susmit/destination
if [ -d "$source_directory" ]; then
Β Β Β  Β Β Β Β Β Β Β  for file in "$source_directory"/*; do
Β Β Β  Β Β Β Β Β Β Β  if [ -f "$file" ]; then
Β Β Β Β Β Β Β Β Β Β Β  Β Β Β Β Β Β Β Β Β Β Β  # Move all regular files to the destination directory
Β Β Β Β Β Β Β Β Β Β Β  Β Β Β Β Β Β Β Β Β Β Β  mv "$file" "$destination_directory/"
Β Β Β Β Β Β Β Β Β Β Β  Β Β Β Β Β Β Β Β Β Β Β  echo "Moved: $file to $destination_directory/"
Β Β Β  Β Β Β Β Β Β Β  fi
Β Β Β  Β Β Β Β Β Β Β  done
else
Β Β Β  Β Β Β Β Β Β Β  echo "Source directory not found: $source_directory"
fi
EXPLANATION

At first, the source_directory and the destination_directory will be defined with a source directory and a destination directory. Then, the current contents of the source directory and the destination directory will be printed on the terminal.

After that, the if [ -d "$source_directory" ]; then checks if the source directory specified by the variable β€˜source_directory’ exists. If exists, for file in "$source_directory"/*; do iterates over each file in the source directory. And if [ -f "$file" ]; then checks if the current iteration entity is a regular file. If so, then the mv "$file" "$destination_directory/" will move all files from the source directory to the destination directory one by one.

For loop in Bash directory has removed two files from source directory to destination directory.

Conclusion

To sum up, this article has discussed different approaches to doing different file operations and directory operations using a for loop. I hope these will help you to use the for loop in the Bash directory more effectively.

People Also Ask

How do I loop through a directory in Bash?

To loop through files in a directory in Bash, you can develop a Bash script with a recursive function that takes the path of the target directory as the initial argument. Then, the function will iterate through all the entities in the directory and call itself whenever one of those entries is a directory. The syntax for looping through a directory by using a for loop is:

#!/bin/bash

for file in /path/to/directory/*; do
    # Operations to perform
    echo "Processing $file"
done

What is the use of the for loop in Bash?

In bash script, a for loop iterates over a sequence of items. It allows programmers to execute commands repeatedly for each item in the specified list. It eases programmers’ intention to automate the long task for a specific time.

How do I check if multiple directories exist in Bash?

To check if multiple directories exist in Bash, you can use a test operator -d with the directory name inside the if statement‘s condition. This will check if it exists and is a directory simultaneously. The syntax for this is:

#!/bin/bash

if [ -d directory_name ]; then

Β  echo "Directory exists."
else
Β  echo "Directory does not exist."
fi

How do I get the list of directories in Bash?

To get the list of files, directories, and subdirectories in any specific directory, use the ls command. This will print all the entities of the current directory. To show all entities, including hidden files and folders, execute the command ls -a.

How do I see how many files are in a directory in Bash?

To see how many files are in a directory in Bash, use the command ls -l | wc -l. This will list all contents of a specific directory in a long list format and redirect it to the wc -l command. Here, the wc command will count the line number of the output of the ls command, which means the file number in that specific directory.

How to create multiple directories in a single command in Bash?

To create multiple directories in a single command in Bash, you can use the mkdir command followed by directory names. The proper syntax for creating multiple directories is: mkdir directory_1 directory_2 directory_3 .. directory_N.

Related Articles


<< Go Back to For Loop in Bash |Β Loops in Bash | Bash Scripting Tutorial

Rate this post
Susmit Das Gupta

Hello everyone. I am Susmit Das Gupta, currently working as a Linux Content Developer Executive at SOFTEKO. I am a Mechanical Engineering graduate from Bangladesh University of Engineering and Technology. Besides my routine works, I find interest in going through new things, exploring new places, and capturing landscapes. Read Full Bio

Leave a Comment