Bash: Meaning of “[: too many arguments
47
16
|
I couldn't find any one simple straightforward resource spelling out the meaning of and fix for the following BASH shell error, so I'm posting what I found after researching it.
The error:
Google-friendly version:
bash open square bracket too many arguments .
Context: an if condition in single square brackets with a simple comparison operator like equals, greater than etc, for example:
| ||||
|
90
|
If your
$VARIABLE is a string containing spaces or other special characters, and single square brackets are used (which is a shortcut for the test command), then the string may be split out into multiple words. Each of these is treated as a separate argument.
So that one variable is split out into many arguments.
The same will be true for any function call that puts down a string containing spaces or other special characters.
Easy fix
Wrap the variable output in double quotes, forcing it to stay as one string (therefore one argument). For example,
An alternate fix is to use double square brackets (which is a shortcut for the
new test command).
This exists only in bash (and apparently korn and zsh) however, and so may not be compatible with default shells called by
/bin/sh etc. This means on some systems, for example, it might work from the console but not from cron , depending on how everything is configured.
It would look like this:
|
3
| echo "*file 2" | grep -o ^. prints * .
Since you have a command substitution outside double quotes, it undergoes globbing (a.k.a. wildcard matching a.k.a. filename generation) and word splitting. If the current directory is not empty,
* expands to the list of files in the current directory. Each file becomes one token in the [ command, which is highly likely to be a syntax error.
The problem is that you didn't use double quotes around the command substitution. Always use double quotes around variable and command substitutions unless you have a good reason to omit them.
See Why does my shell script choke on whitespace or other special characters? for a more detailed explanation.
|