Quoting within $(command substitution) in Bash


SUBMITTED BY: Guest

DATE: June 2, 2014, 12:36 p.m.

FORMAT: Text only

SIZE: 1.4 kB

HITS: 5752

  1. In order from worst to best:
  2. DIRNAME="$(dirname $FILE)" will not do what you want if $FILE contains whitespace or globbing characters \[?*.
  3. DIRNAME=`dirname "$FILE"` is technically correct, but backticks are not recommended for command expansion because of the extra quoting issues when nesting them.
  4. 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.
  5. 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.
  6. To improve even further:
  7. DIRNAME="$(dirname -- "$FILE")" works if $FILE starts with a dash.
  8. 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.
  9. 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:
  10. foo "$(bar "$(baz "$(ban "bla")")")"
  11. You do not want to try that with backticks.

comments powered by Disqus