Please write me a bash script to print all files of the directory with a certain suffix in the terminal?
Certainly! Below is a simple Bash script that lists all files in a specified directory that have a certain suffix (file extension). You can customize the directory path and the file suffix as needed.
#!/bin/bash
# Check if the correct number of arguments is provided
if [ "$#" -ne 2 ]; then
echo "Usage: $0 <directory_path> <file_suffix>"
exit 1
fi
# Assign arguments to variables for better readability
DIRECTORY="$1"
SUFFIX="$2"
# Check if the specified directory exists
if [ ! -d "$DIRECTORY" ]; then
echo "Error: Directory '$DIRECTORY' does not exist."
exit 1
fi
# Use 'find' to list files with the specified suffix
echo "Files in '$DIRECTORY' with suffix '$SUFFIX':"
find "$DIRECTORY" -type f -name "*.$SUFFIX"
How to Use This Script
- Save the script to a file, for example,
list_files.sh. - Make the script executable by running:
chmod +x list_files.sh - Run the script by providing the directory path and the file suffix (without the dot) as arguments. For example:
./list_files.sh /path/to/directory txt
Example
If you want to find all .jpg files in the /home/user/pictures directory, you would run:
./list_files.sh /home/user/pictures jpg
This will print all .jpg files in the specified directory to the terminal.