Writing shell scripts to automate backups, process server logs, or validate user input is standard for Linux system administrators. However, executing a script only to have it terminate abruptly with bash: [: too many arguments or [: line 12: too many arguments breaks automated cron execution. This syntax error points directly to variable word splitting inside conditional test statements.
What Causes the “Too Many Arguments” Error in Bash?
In Bash, single brackets [ ... ] are an alias for the POSIX test command. Key culprits include:
- Unquoted Variables with Spaces: When a variable containing spaces (e.g.
VAR="John Doe") is expanded unquoted inside single brackets ([ $VAR = "admin" ]), Bash splits it into multiple tokens ([ John Doe = "admin" ]), giving the test command too many positional parameters. - Unquoted Variables that Expand Empty: Variables that evaluate to nothing leaving operators with missing operands.
- Using Single Brackets for Pattern Matching: Attempting to use regex or glob wildcards inside single brackets instead of double brackets.
- Unescaped Special Characters: Passing string values with unescaped comparison operators (like
>or<).
1. Enclose Variables in Double Quotes
Quoting variables prevents the shell from performing word splitting and pathname expansion on whitespace.
# INCORRECT (Fails if $FILENAME contains spaces):
if [ $FILENAME = "backup.tar.gz" ]; then
echo "File matched"
fi
# CORRECT (Double quotes preserve the string as a single token):
if [ "$FILENAME" = "backup.tar.gz" ]; then
echo "File matched"
fi
By wrapping "$FILENAME" in double quotes, even a value like "daily backup 2026.tar.gz" is treated as a single argument, preventing the error completely.
2. Upgrade to Modern Bash Double Brackets [[ … ]]
The modern Bash keyword [[ ... ]] handles whitespace gracefully and does not perform word splitting on variables.
# RECOMMENDED BASH SYNTAX:
if [[ $FILENAME == "backup.tar.gz" ]]; then
echo "File matched"
fi
Within [[ ... ]], quotes around simple variables are optional, and you gain access to pattern matching (*) and regular expression operators (=~).
3. Fix String Length Checks (-z and -n)
Checking if a variable is empty without quotes frequently causes argument count errors.
# INCORRECT:
if [ -z $USER_INPUT ]; then
echo "Empty"
fi
# CORRECT:
if [ -z "$USER_INPUT" ]; then
echo "Empty"
fi
If $USER_INPUT contains spaces, unquoted expansion evaluates to [ -z word1 word2 ], throwing the “too many arguments” error.
4. Check for Spaces Around Brackets
Bash requires whitespace immediately inside brackets.
# INCORRECT (Syntax error):
if ["$VAR" = "test"]; then
# CORRECT (Spaces on both sides of brackets):
if [ "$VAR" = "test" ]; then
Ensure a space separates the opening bracket [ and the closing bracket ] from all interior expressions.