by codedokode · 8y ago · 0 comments
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 [[.
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. 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. 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...
parent_dir = "$(basename "$dir")"