Bash File Searching: Exercises, Solutions, and Explanations
1.
Write a Bash script that searches for a file named "output.txt" in the current directory.
Code:
#!/bin/bash
# Search for file named "output.txt" in the current directory
if [ -f "output.txt" ]; then
echo "File 'output.txt' found in the current directory."
else
echo "File 'output.txt' not found in the current directory."
fi
Output:
File 'output.txt' found in the current directory.
Explanation:
In the exercise above,
- if [ -f "output.txt" ]; then: This line checks if a file named "output.txt" exists in the current directory.
- [ -f "output.txt" ] is a conditional expression that tests if "output.txt" exists and is a regular file.
- If the file exists, the condition returns true, and the code inside the "if" block is executed.
- echo "File 'output.txt' found in the current directory.": If the file "output.txt" exists in the current directory, this line prints a message indicating that the file is found.
- else: If the condition in the "if" statement evaluates to false, meaning "output.txt" does not exist or is not a regular file, the code inside the "else" block is executed.
- echo "File 'output.txt' not found in the current directory.": In the "else" block, this line prints a message indicating that the file "output.txt" is not found in the current directory.
- fi: This marks the end of the "if" statement.
2.
Write a Bash script that searches for a file with a specific name provided as an argument to the script.
Code:
#!/bin/bash
# Check if an argument is provided
if [ $# -ne 1 ]; then
echo "Usage: $0 <filename>"
exit 1
fi
# Get the filename from the command line argument
filename="$1"
# Check if the file exists in the current directory
if [ -f "$filename" ]; then
echo "File '$filename' found in the current directory."
else
echo "File '$filename' not found in the current directory."
fi
Output:
ad@DESKTOP-3KE0KU4:~$ ./test1.sh input.txt File 'input.txt' found in the current directory. ad@DESKTOP-3KE0KU4:~$ ./test1.sh document.doc File 'document.doc' not found in the current directory.
Explanation:
In the exercise above,
- if [ $# -ne 1 ]; then: Checks if the number of arguments provided is not equal to 1.
- echo "Usage: $0 <filename>": Prints a usage message if the number of arguments is incorrect.
- exit 1: Exits the script with a non-zero status code to indicate an error.
- filename="$1": Assigns the first argument provided to the variable 'filename'.
- if [ -f "$filename" ]; then: Checks if the file with the provided filename exists in the current directory.
- echo "File '$filename' found in the current directory.": Prints a message if the file is found.
- echo "File '$filename' not found in the current directory.": Prints a message if the file is not found.
3.
Write a Bash script that searches for files modified within the last 3 days in the current directory.
Code:
#!/bin/bash
# Get the current time in seconds since the epoch
current_time=$(date +%s)
# Calculate the time 3 days ago in seconds since the epoch
three_days_ago=$((current_time - (3 * 24 * 60 * 60)))
# Iterate over each file in the current directory
for file in *; do
# Check if the file was modified within the last 3 days
if [ -f "$file" ] && [ $(stat -c %Y "$file") -ge "$three_days_ago" ]; then
echo "$file"
fi
done
Output:
abc.sh erorrrr.log input1.txt input.txt old_error.log test1.sh test.sh
Explanation:
In the exercise above,
- current_time=$(date +%s): Gets the current time in seconds since the epoch.
- three_days_ago=$((current_time - (3 24 60 * 60))): Calculates the time 3 days ago in seconds since the epoch.
- for file in *; do: Iterates over each file in the current directory.
- if [ -f "$file" ] && [ $(stat -c %Y "$file") -ge "$three_days_ago" ]; then: Checks if the file is a regular file (-f) and if its modification time (obtained using stat -c %Y "$file") is greater than or equal to the time 3 days ago.
- echo "$file": Prints the filename if it meets the criteria.
4.
Write a Bash script that searches for files larger than 1KB in the current directory.
Code:
#!/bin/bash
# Iterate over each file in the current directory
for file in *; do
# Check if the file size is greater than 1KB (1024 bytes)
if [ -f "$file" ] && [ $(stat -c %s "$file") -gt 1024 ]; then
echo "$file"
fi
done
Output:
output.txt
Explanation:
In the exercise above,
- for file in *; do: Iterates over each file in the current directory.
- if [ -f "$file" ] && [ $(stat -c %s "$file") -gt 1024 ]; then: Checks if the file is a regular file (-f) and if its size in bytes (obtained using stat -c %s "$file") is greater than 1024 bytes (1KB).
- echo "$file": Prints the filename if it meets the criteria.
5.
Write a Bash script that searches for empty files in the current directory.
Code:
#!/bin/bash
# Iterate over each file in the current directory
for file in *; do
# Check if the file is empty (has size 0)
if [ -f "$file" ] && [ ! -s "$file" ]; then
echo "$file"
fi
done
Output:
input1.txt input.txt
Explanation:
In the exercise above,
- for file in *; do: Iterates over each file in the current directory.
- if [ -f "$file" ] && [ ! -s "$file" ]; then: Checks if the file is a regular file (-f) and if its size (obtained using ! -s "$file") is 0, indicating it's empty.
- echo "$file": Prints the filename if it meets the criteria.
6.
Write a Bash script that searches for files with a specific extension (e.g., "txt") in the current directory.
Code:
#!/bin/bash
# Enable globbing to include hidden files
shopt -s dotglob
# Specify the extension to search for
extension="txt"
# Iterate over each file in the current directory
for file in *; do
# Check if the file has the specified extension
if [ "${file##*.}" = "$extension" ]; then
echo "$file"
fi
done
Output:
input1.txt input.txt
Explanation:
In the exercise above,
- extension="txt": Specifies the extension to search for.
- for file in *; do: Iterates over each file in the current directory.
- ${file##*.}: Extracts the file extension.
- if [ "${file##*.}" = "$extension" ]; then: Checks if the extracted extension matches the specified extension.
- echo "$file": Prints the filename if it has the specified extension.
7.
Write a Bash script that searches for files containing a specific string provided as an argument to the script.
Code:
#!/bin/bash
# Check if the argument is provided
if [ $# -eq 0 ]; then
echo "Usage: $0 <search_string>"
exit 1
fi
# Extract the search string from the command line argument
search_string="$1"
# Iterate over each file in the current directory
for file in *; do
# Check if the file is a regular file and contains the search string
if [ -f "$file" ] && [ $(grep -q "$search_string" "$file"; echo $?) -eq 0 ]; then
echo "$file"
fi
done
Output:
ad@DESKTOP-3KE0KU4:~$ ./test1.sh shell file2.txt output.txt sample.txt
Explanation:
In the exercise above,
- $# -eq 0: Checks if no command-line arguments are provided.
- echo "Usage: $0 <search_string>": Prints usage instructions if no argument is provided.
- search_string="$1": Extracts the search string from the command-line argument.
- for file in *; do: Iterates over each file in the current directory.
- if [ -f "$file" ] && [ $(grep -q "$search_string" "$file"; echo $?) -eq 0 ]; then: Checks if the file is a regular file and contains the search string using grep.
- echo "$file": Prints the filename if it contains the search string.
8.
Write a Bash script that searches for files owned by a specific user in the current directory.
Code:
#!/bin/bash
# Check if the username is provided as an argument
if [ $# -eq 0 ]; then
echo "Usage: $0 <username>"
exit 1
fi
# Extract the username from the command-line argument
username="$1"
# Search for files owned by the specified user in the current directory
find . -maxdepth 1 -type f -user "$username"
Output:
ad@DESKTOP-3KE0KU4:~$ ./test1.sh ad ./.bash_history ./.bash_logout ./.bashrc ./.profile ./.viminfo ./abc.sh ./document.txt ./erorrrr.log ./file2.txt ./input.txt ./input1.txt ./nums.txt ./old_error.log ./output.txt ./sample.txt ./test.sh ./test1.sh ad@DESKTOP-3KE0KU4:~$ ./test1.sh us find: 'us' is not the name of a known user
Explanation:
In the exercise above,
- $# -eq 0: Checks if no command-line arguments are provided.
- echo "Usage: $0 <username>": Prints usage instructions if no argument is provided.
- username="$1": Extracts the username from the command-line argument.
- find . -maxdepth 1 -type f -user "$username": Searches for files (-type f) owned by the specified user (-user "$username") in the current directory (.) without descending into subdirectories (-maxdepth 1).
9.
Write a Bash script that searches for symbolic links in the current directory.
Code:
#!/bin/bash
# Search for symbolic links in the current directory
find . -maxdepth 1 -type l
Output:
./my_link
Explanation:
In the exercise above,
- find .: Start searching from the current directory.
- -maxdepth 1: Limits the search to the current directory without descending into subdirectories.
- -type l: Specifies that only symbolic links should be considered.
10.
Write a Bash script that searches for files with execute permissions in the current directory.
Code:
#!/bin/bash
# Search for files with execute permissions in the current directory
find . -maxdepth 1 -type f -executable
Output:
./test.sh ./test1.sh
Explanation:
In the exercise above,
- find .: Start searching from the current directory.
- -maxdepth 1: Limits the search to the current directory without descending into subdirectories.
- -type f: Specifies that only regular files should be considered (not directories or other types of files).
- -executable: Filters the search to include only files with execute permissions.
Bash Editor:
More to Come !
Do not submit any solution of the above exercises at here, if you want to contribute go to the appropriate exercise page.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/bash-script-exercises/seaching-for-files.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics