编写一个shell脚本,接受一个目录作为参数,递归遍历该目录下的所有文件以及子文件夹,统计输出.log文件与.txt文件数量、及相关文件路径
时间: 2024-04-15 08:27:50 浏览: 185
Sure! Here's a shell script that accepts a directory as a parameter, recursively traverses all files and subdirectories within that directory, and outputs the count of `.log` and `.txt` files along with their respective file paths:
```bash
#!/bin/bash
# Function to recursively traverse directory
traverse_directory() {
local dir=$1
# Loop through each file and subdirectory in the given directory
for file in "$dir"/*; do
if [ -f "$file" ]; then
# Check if the file has .log or .txt extension
if [[ $file == *.log ]]; then
echo "Log file found: $file"
((log_count++))
elif [[ $file == *.txt ]]; then
echo "Text file found: $file"
((txt_count++))
fi
elif [ -d "$file" ]; then
# Recursively call the function for subdirectories
traverse_directory "$file"
fi
done
}
# Check if directory is provided as argument
if [ $# -eq 0 ]; then
echo "Please provide a directory as an argument."
exit 1
fi
# Initialize file count variables
log_count=0
txt_count=0
# Call the function to traverse the directory
traverse_directory "$1"
# Output the file counts
echo "Number of log files: $log_count"
echo "Number of text files: $txt_count"
```
To use this script, save it to a file (e.g., `file_count.sh`), make it executable using `chmod +x file_count.sh`, and then run it with the desired directory as the argument:
```bash
./file_count.sh /path/to/directory
```
Replace `/path/to/directory` with the actual directory path you want to traverse. The script will recursively search for `.log` and `.txt` files and print their counts along with the file paths.
阅读全文