For loop to list all files in a directory

Here is the simple bash script that uses a “for” loop to list all files in a directory:

Syntax of for loop:

for ((initialization; condition; update)); do

# Commands to be executed in each iteration

done

Here are the steps to create a simple Bash script that uses a for loop to list all files in a directory.

Create a new file as mentioned below.
list_files.sh
Copy and paste below simple Bash script that uses a for loop to list all files in a directory.
# Bash script that uses a “for” loop to list all files in a directory:

#!/bin/bash

# Specify the directory path

directory_path="/path/to/your/directory"

# Check if the directory exists

if [ -d "$directory_path" ]; then

# Use a for loop to iterate over each file in the directory

for file in "$directory_path"/*; do

# Check if the item is a file (not a directory)

if [ -f "$file" ]; then

echo "File: $file"

fi

done

else

echo "Directory not found: $directory_path"

fi

Make sure to replace “/path/to/your/directory” with the actual path of the directory you want to list files from.

Here’s a breakdown of the script:

1. “directory_path=”/path/to/your/directory”“: Set the variable “directory_path” to the path of the directory you want to list files from.

2. “if [ -d “$directory_path” ]; then”: Check if the specified directory exists.

3. “for file in “$directory_path”/*; do”: Use a “for” loop to iterate over each item (file or directory) in the specified directory.

4. “if [ -f “$file” ]; then”: Check if the current item is a file (not a directory).

5. “echo “File: $file”“: If the item is a file, print its name.

6. “fi”: Close the inner “if” statement.

7. “done”: Mark the end of the “for” loop.

8. “else”: If the specified directory doesn’t exist, print an error message.

9. “echo “Directory not found: $directory_path““: Print an error message indicating that the directory was not found.

Run the script by making it executable:
chmod +x list_files.sh
And then execute it:
./list_files.sh

How do you feel about this post? Drop your comments below..