From cb0e8deb6ecd43552501e02e3293188d119d6280 Mon Sep 17 00:00:00 2001 From: koalaman Date: Mon, 5 Sep 2016 16:49:09 -0700 Subject: [PATCH] Updated SC2086 (markdown) --- SC2086.md | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/SC2086.md b/SC2086.md index ce01013..d22c232 100644 --- a/SC2086.md +++ b/SC2086.md @@ -40,7 +40,7 @@ echo "This $variable is quoted $(and now this "$variable" is too)" ``` ### Exceptions -Sometimes you want to split on spaces, like when building a command line. +Sometimes you want to split on spaces, like when building a command line: ```sh options="-j 5 -B" @@ -63,3 +63,20 @@ make_with_flags file To split on spaces but not perform glob expansion, Posix has a `set -f` to disable globbing. You can disable word splitting by setting `IFS=''`. +Similarly, you might want an optional argument: + +```sh +debug="" +[[ $1 == "--trace-commands" ]] && debug="-x" +bash $debug script +``` + +Quoting this doesn't work, since in the default case, `"$debug"` would expand to one empty argument while `$debug` would expand into zero arguments. In this case, you can use an array with zero or one elements as outlined above, or you can use an unquoted expansion with an alternate value: + +```sh +debug="" +[[ $1 == "--trace-commands" ]] && debug="yes" +bash ${debug:+"-x"} script +``` + +This is better than an unquoted value because the alternative value can be properly quoted, e.g. `wget ${output:+ -o "$output"}`. \ No newline at end of file