0

What I learnt: $(...) is nested execution

Questions: Do I need to put double quotation marks for $(expression) to check that string is empty or not? if it is a variable, we do not need (-z "$var"), we can just use (-z $var) right? What if the string generated is an expression? for example, if I want to check whether the string is empty or not, (-z $(expression)), do I need double-quotes for $(expression) (seems to work fine but just want to make sure)

Barmar
  • 741,623
  • 53
  • 500
  • 612
Bob
  • 3
  • 4
  • `[ -z $(expression) ]` looks fine if you're only testing the easy cases, but it doesn't work reliably. Quote. Always. Bash has too many corner cases that you don't find unless you're testing with oddball scenarios to rely on "looks good to me" testing. – Charles Duffy Feb 10 '21 at 21:31
  • Don't you mean `[ -z "$var" ]` rather than `(-z "$var")`? – Barmar Feb 10 '21 at 21:32
  • 1
    No, you can't just use `-z $var`. If the variable is empty, then you'll just be testing if `-z` is a non-empty string, returning true. But if the variable *isn't* empty, it is subject to pathname expansion and word-splitting, which could result in a run time error when `test`/`[` gets too many arguments. – chepner Feb 10 '21 at 21:33
  • 1
    Also, `var` can be something like `foo -a 1 = 2`, or `foo -o 1 = 1`, forcing a truthy or falsey result, whichever the person feeding in malicious data prefers, no matter if your test is `-n` or `-z`. – Charles Duffy Feb 10 '21 at 21:33

0 Answers0