3 ms·
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
by codedokode 8y ago
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 [[.
- zeroimpl 8y agoYou just add quotes around $dir. Bash understands the quotes properly/recursively. parent_dir = "$(basename "$dir")"
- codedokode 8y agoSo I finally found the answer. Thanks.
- 8xde0wcNwpslOw 8y agoBear 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.
- rossy 8y agoYou 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.
- deleted 8y ago[deleted]
- koala_man 8y ago$(..) 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.
- thisacctforreal 8y ago$( 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_chap02.html#tag_02_06_03 http://pubs.opengroup.org/onlinepubs/009695399/utilities/xcu...