Linux Bash脚本if语句出现[: too many arguments错误原因排查
[: too many arguments Error in Your Bash Script Let's walk through exactly what's going wrong and how to fix your script step by step.
The Root Cause of the Error
The main issue is how you're capturing the output of wc -w. When you run wc -w $filename, it returns two values: the number of words and the filename (e.g., 42 myfile.txt). When you assign this to $WC and use it in [ $WC -gt 33 ], Bash splits the string into separate arguments. This turns your condition into something like:
[ 42 myfile.txt -gt 33 ]
The test command (shortened to [) expects a single number on each side of -gt, so the extra filename argument triggers the too many arguments error.
Other Syntax Issues in Your Script
You've also got a couple of minor syntax problems that would cause errors even if the wc issue was fixed:
- Incorrect variable assignment +
cd: WritingIN_FOLDER=period_to_import cd $IN_FOLDERonly sets theIN_FOLDERvariable temporarily for thecdcommand. The variable won't be available in the rest of your script unless you split this into two lines or use&&. - Missing statement separators: Your script runs commands together without newlines or semicolons (e.g.,
WC=$(wc -w $filename) if [ $WC -gt 33 ]), which Bash can't parse correctly. - Unquoted variables: If any filenames have spaces,
$filenamewill split into multiple arguments and break commands likewcorrm.
Fixed Script
Here's the corrected version with all issues addressed:
IN_FOLDER=period_to_import cd "$IN_FOLDER" || exit # Exit immediately if cd fails (prevents accidental deletions!) for filename in *; do # Capture ONLY the word count (no filename) by redirecting the file content to wc WC=$(wc -w < "$filename") # Use quotes around variables to handle spaces if [ "$WC" -gt 33 ]; then rm "$filename" fi done
Key Fixes Explained
wc -w < "$filename": This sends the file's content directly towcinstead of passing the filename as an argument. Nowwconly outputs the word count (a single number), so$WCwon't have extra text.- Quoted variables (
"$IN_FOLDER","$filename","$WC"): Ensures spaces or special characters in values don't break command parsing. cd "$IN_FOLDER" || exit: Adds a safety check—if the folder doesn't exist, the script stops instead of runningrmin your current directory (which could be disastrous!).- Proper line breaks and semicolons: Makes the script's structure clear and parsable by Bash.
内容的提问来源于stack exchange,提问作者Pedro

