Hacker News new | past | comments | ask | show | jobs | submit login

How does one properly quote an argument for a command that can contain spaces?

For example:

    parent_dir = "$(basename $dir)"
How to quote $dir here? What if it contains spaces or other special characters?

That's what I dislike about Bash.

Also, always start your scripts with

    set -e
This prevents script from running after error, without any messages though.

Also, I always make mistakes when using [ and [[.




You quote it like this:

    parent_dir="$(basename "$dir")"
Quotes are syntactic in bash, so it understands that the outer pair of quotes are surrounding the command substitution and the inner pair are inside it. This will work regardless of any spaces or special characters in $dir.


$(..) is its own context so you just put double quotes around any variables like you normally would:

    parent_dir="$(basename "$dir")"
[ and [[ can indeed be tricky. You may find ShellCheck useful, since it recognizes common problems like [ a=b ], [-e .bashrc], [ 1 > 2 ], [ -n var ], [ false ] and several others.


$( allows any syntax until a non-escaped ). It's Command Substitution[1], and they run in "subshells".

    echo hello "$(
        echo hello \
        | sed 's,hello,world,g'
    )"
[ is an actual binary file that gets invoked, called test. You can "man [" or "man test" to learn about all of its uses.

I use [ exclusively, but with && and ||, instead of -a and -o respectfully.

e.g. [ -e "$file" ] && [ -w "$file" ] instead of [ -e "$file" -a -w "$file" ].

[1] http://pubs.opengroup.org/onlinepubs/009695399/utilities/xcu...


You just add quotes around $dir. Bash understands the quotes properly/recursively.

    parent_dir = "$(basename "$dir")"


So I finally found the answer. Thanks.


Bear in mind (pointed by the article as well) that variable assignment doesn't allow spaces around the equals sign, and that in this case the outer parentheses are unnecessary anyway.




Join us for AI Startup School this June 16-17 in San Francisco!

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: