Here's a part of my script that is telling me that I have too many arguments on line 3:

#!/bin/bash
export LC_ALL='C'
if [ `echo "*file 2" | grep -o ^.` = '.' ]
then
    echo success
fi

Anybody know why? As far as I can tell, I'm just comparing two arguments, "*" and "."

up vote 4 down vote accepted

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.

if [ "$(echo "*file 2" | grep -o ^.)" = '.' ]

See Why does my shell script choke on whitespace or other special characters? for a more detailed explanation.

  • Thanks, I'm still new to shell scripting, so all help is appreciated! – Aaron Oct 17 '14 at 0:19

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.