From 0c7d198e5a87bff09a7753e9369a57adaffc735d Mon Sep 17 00:00:00 2001 From: Vidar Holen Date: Thu, 26 Aug 2021 17:24:22 -0700 Subject: [PATCH] Updated SC2016 (markdown) --- SC2016.md | 29 ++++++++++++++++++++--------- 1 file changed, 20 insertions(+), 9 deletions(-) diff --git a/SC2016.md b/SC2016.md index 334367a..be12abc 100644 --- a/SC2016.md +++ b/SC2016.md @@ -4,33 +4,44 @@ ```sh name=World -echo 'Hello $name' +echo 'Hello $name' # Outputs Hello $name ``` ### Correct code: ```sh name=World -echo "Hello $name" +echo "Hello $name" # Outputs Hello World ``` ### Rationale: -Single quotes prevent expansion of everything, including variables and command substitution. +ShellCheck found an expansion like `$var`, `$(cmd)`, or `` `cmd` `` in single quotes. -If you want to use the values of variables and such, use double quotes instead. +Single quotes express all such expansions. If you want the expression to expand, use double quotes instead. -Note that if you have other items that needs single quoting, you can use both in a single word: +If switching to double quotes would require excessive escaping of other metacharacters, note that you can mix and match quotes in the same shell word: ```sh -echo '$1 USD is '"$rate GBP" +dialog --msgbox "Filename $file may not contain any of: "'`&;"\#%$' 10 70 ``` ### Exceptions -If you want `$stuff` to be a literal dollar sign followed by the characters "stuff", you can [[ignore]] this message. +If you know that you want the expression literally without expansion, you can [[ignore]] this message: -ShellCheck tries to be smart about it, and won't warn when this is used with awk, perl and similar, but there are some inherent ambiguities like `'I have $1 in my wallet'`, which could be "one dollar" or "whatever's in the first parameter". +``` +# We want this to output $PATH without expansion +# shellcheck disable=SC2016 +echo 'PATH=$PATH:/usr/local/bin' >> ~/.bashrc +``` -In the particular case of `sed`, ShellCheck uses additional heuristics to try to separate cases like `'s/$foo/bar/'` (failing to replace the variable `$foo`) with from the false positives like `'$d'` (delete last line). If you're still triggering these, consider being more generous with your spaces: use `$ { s/foo/bar; }` instead of `${s/foo/bar/;}` +ShellCheck also does not warn about escaped expansions in double quotes: +``` +echo "PATH=\$PATH:/usr/local/bin" >> ~/.bashrc +``` + +### Related resources: + +* StackOverflow: [How do I use variables in single quoted strings?](https://stackoverflow.com/questions/21192420/how-do-i-use-variables-in-single-quoted-strings) \ No newline at end of file