Quoting within $(command substitution) in Bash


SUBMITTED BY: Guest

DATE: May 28, 2014, 7:42 a.m.

FORMAT: Text only

SIZE: 1.5 kB

HITS: 10299

  1. 24 down vote accepted
  2. In order from worst to best:
  3. DIRNAME="$(dirname $FILE)" will not do what you want if $FILE contains whitespace or globbing characters \[?*.
  4. DIRNAME=`dirname "$FILE"` is technically correct, but backticks are not recommended for command expansion because of the extra quoting issues when nesting them.
  5. DIRNAME=$(dirname "$FILE") is correct, but only because this is an assignment. If you use the command substitution in any other context, such as export DIRNAME=$(dirname "$FILE") or du $(dirname "$FILE"), the lack of quotes will cause trouble if the result of the expansion contain whitespace or globbing characters.
  6. DIRNAME="$(dirname "$FILE")" is the recommended way. You can replace DIRNAME= with a command and a space without changing anything else, and dirname receives the correct string.
  7. To improve even further:
  8. DIRNAME="$(dirname -- "$FILE")" works if $FILE starts with a dash.
  9. DIRNAME="$(dirname -- "$FILE"; printf x)" && DIRNAME="${DIRNAME%?x}" works even if $FILE ends with a newline, since $() chops off newlines at the end of output and dirname outputs a newline after the result.
  10. You can nest command expansions as much as you like. With $() you always create a new quoting context, so you can do things like this:
  11. foo "$(bar "$(baz "$(ban "bla")")")"
  12. You do not want to try that with backticks.

comments powered by Disqus