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.
Re:Safe ways to do things in bash
by thisacctforreal on Tuesday May 15, 2018 @04:44AM
(#17072536)
$( 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")"
Re:Safe ways to do things in bash
by codedokode on Monday May 14, 2018 @08:53PM
(#17070741)
So I finally found the answer. Thanks.
Re:Safe ways to do things in bash
by 8xde0wcNwpslOw on Tuesday May 15, 2018 @07:46AM
(#17073237)
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.
For example:
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
This prevents script from running after error, without any messages though.Also, I always make mistakes when using [ and [[.