Generally speaking, in the above assignment, does a subshell can be avoided using the following?
if [ -z "$FOO" ]; then if [ "$BAR" = "baz" ]; then FOO=true else FOO=false fi fi
Yes, and that would be the correct way to write it.
: ${FOO:=$([ "$BAR" = "baz" ] && echo "true" || echo "false" )}
Runs a subshell (which isin most shells involves the costly forking of a process) and is also wrong for several reasons:
- That
${FOO...}expansion is unquoted and therefore subject to split+glob, making it at least a DoS vulnerability (that's one of the examples given at Security implications of forgetting to quote a variable in bash/POSIX shells). echo "false"is run if either[orecho truefails while you want it to be run when[fails only.a && b || cis no proper substitute forif a; then b; else c; fi.
In the ksh93 shell, the subshell and those issues can be avoided with:
: "${FOO:=${ if [ "$VAR" = baz ]; then echo true else echo false fi }}" But that has little advantage over the standard and obvious if statement above.