1

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

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

It works. But I don't understand why. I would think that the quotes around $1 would act to negate the outer quotes. Do you have a link where I can find out more about this?
The context inside $(...) gets evaluated first, then the parent shell's quoting is processed.
"The context inside $(...) gets evaluated first" Ah that makes a lot more sense. Thank you
1

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.)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.