Rucent88
Rucent88

Reputation: 950

How to execute a command with $variable that contains spaces?

In my script I have this line:

[ -z "$(file $1 | grep '256')" ] && echo 256

If $1 contains spaces, then I get the error message

line 11: [: too many arguments

How can I properly quote this so that it is runs correctly?

UPDATE:
I pasted the line from my script incorrectly. The error message is correct for this line

[ -z $(file "$1" | grep '256') ] && echo 256

Upvotes: 1

Views: 86

Answers (2)

tripleee
tripleee

Reputation: 189910

Use double quotes around your variables. Always.

(Well, not always always. There are situations where you want the shell to perform word splitting on a value, but those are a small minority and not something you should expect to understand any time soon.)

However, what you are doing there can simply be replaced with

file "$1" | grep -o '256'

Shell quoting is a common FAQ; it's poorly understood, but not hard at all. See e.g. http://mywiki.wooledge.org/Quotes (Bash-specific, but generally applicable to the entire Bourne family of shells.)

Upvotes: 1

that other guy
that other guy

Reputation: 123680

Double quote the $1:

[ -z "$(file "$1" | grep '256')" ] && echo 256

PS: The line you posted would not cause the error you're referring to. Either you copied the error from another version, or you have another misquoted line in your script.

Upvotes: 2

Related Questions