Bash脚本报错修复:无法解析elif子句及命令未找到问题
Fixing Your Bash Script for Moving Empty Files
Let's walk through fixing your script step by step, since there are a few syntax and logic issues causing those errors. First, here's the corrected, fully functional version of your script:
#!/bin/bash # Script to move empty files from current directory into the subdirectory Empty_Files # Usage: ./move_empty subdirectory="Empty_Files" # Check if the subdirectory exists; create it if not if [ -d "$subdirectory" ]; then echo "$subdirectory exists!" else mkdir -p "$subdirectory" echo "Empty_Files subdirectory created" fi # Find all non-hidden, regular empty files in the current directory empty_files=$(find . -maxdepth 1 -type f ! -name ".*" -size 0) # Check if there are any empty files if [ -n "$empty_files" ]; then echo "Found empty files:" echo "$empty_files" echo -n "Would you like to move these files to $subdirectory? (Y/N): " read useranswer # Handle user input if [[ "$useranswer" =~ ^[Yy]$ ]]; then # Move each empty file (using xargs to handle spaces in filenames) echo "$empty_files" | xargs -I {} mv {} "$subdirectory/" echo "Successfully moved empty files to $subdirectory" elif [[ "$useranswer" =~ ^[Nn]$ ]]; then echo "No files were moved." else echo "Invalid input. Please enter Y or N." exit 1 fi else echo "No empty non-hidden files found in the current directory." exit 55 fi
Let's break down the fixes for your original errors:
- Incorrect directory check: Your script used
-f(for regular files) to verify the subdirectory exists—we replaced this with-dwhich properly checks for directories. We also removed the hardcoded path to make the script portable, using the$subdirectoryvariable instead. - Broken variable assignment: Bash doesn't use a
$when assigning variables, and pipinglsinto a variable is unreliable for filenames (especially those with spaces). We usedfindto safely locate non-hidden empty files instead. - Invalid condition syntax: Your
if [ $useranswer = "y" || "Y" ]was wrong Bash syntax. We switched to[[ "$useranswer" =~ ^[Yy]$ ]]to cleanly match uppercase/lowercase Y, and added the missingthenkeyword to theelifclause (which caused your parsing error). - Wrong
readsyntax:read $useranswershould beread useranswer—you don't use$when assigning input to a variable. - Logic flaws for multiple files: The original script didn't account for multiple empty files. Using
findandxargsensures we handle all empty files correctly, even those with spaces in names. - Improved flow: We moved the "no empty files" check to an
elseclause, making the logic more intuitive and eliminating messy nested conditionals.
内容的提问来源于stack exchange,提问作者drew197




