{ "conversations": [ [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: `$` is not used specially and should therefore be escaped. [SC1000]"},{"from": "gpt", "value": "# `$` is not used specially and should therefore be escaped.\n _Note: Removed in [v0.3.3 - 2014-05-29](https://github.com/koalaman/shellcheck/blob/2e5c56b27034492134be1538c1e1e6a533ca791a/CHANGELOG.md#removed-1)_\n \n ### Problematic code:\n \n ```sh\n echo \"$\"\n ```\n \n ### Correct code:\n \n ```sh\n echo \"\\$\"\n ```\n \n ### Rationale:\n `$` is special in double quotes, but there are some cases where it's interpreted literally:\n \n 1. Following a backslash: `echo \"\\$\"`\n 2. In a context where the shell can't make sense of it, such as at the end of the string, (`\"foo$\"`) or before some constructs (`\"$'foo'\"`).\n \n To avoid relying on strange and shell-specific behavior, any `$` intended to be literal should be escaped with a backslash.\n \n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: This `\\o` will be a regular 'o' in this context. [SC1001]"},{"from": "gpt", "value": "## This `\\o` will be a regular 'o' in this context.\n \n ### Problematic code:\n \n ```sh\n # Want literal backslash\n echo Yay \\o/\n \n # Want other characters\n bell=\\a\n ```\n \n ### Correct code:\n \n ```sh\n echo 'Yay \\o/'\n \n bell=\"$(printf '\\a')\"\n ```\n \n ### Rationale:\n \n You have escaped something that has no special meaning when escaped. The backslash will be simply be ignored.\n \n If the backslash was supposed to be literal, single quote or escape it.\n \n If you wanted it to expand to something, rewrite the expression to use `printf` (or in bash, `$'\\t'`). If the sequence in question is `\\n`, `\\t` or `\\r`, you instead get a [[SC1012]] that describes this. \n \n ### Exceptions\n \n None. ShellCheck (as of [2017-07-03](https://github.com/koalaman/shellcheck/commit/31bb02d6b794f248f732643d744f63bec615b1f7), commit [`31bb02d6`](https://github.com/koalaman/shellcheck/commit/31bb02d6b794f248f732643d744f63bec615b1f7)) will not warn when the first letter of a command is unnecessarily escaped, as this is frequently used to suppress aliases interactively. \n \n ### Related resources:\n \n * https://www.gnu.org/software/bash/manual/html_node/Aliases.html\n * https://www.gnu.org/software/bash/manual/html_node/Quoting.html\n * https://tiswww.case.edu/php/chet/bash/bash.html\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Want to escape a single quote? `echo 'This is how it'\\''s done'`. [SC1003]"},{"from": "gpt", "value": "## Want to escape a single quote? `echo 'This is how it'\\''s done'`.\n \n (Note: in v0.4.6, the error message was accidentally missing the backslash)\n \n ### Problematic code:\n \n ```sh\n echo 'This is not how it\\'s done'.\n ```\n \n ### Correct code:\n \n ```sh\n echo 'This is how it'\\''s done'.\n ```\n \n \n ### Rationale\n \n In POSIX shell, the shell cares about nothing but another single-quote to terminate the quoted segment. Not even backslashes are interpreted.\n \n [POSIX.1 Shell Command Language § 2.2.2 Single Quotes](http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_02_02):\n \n > Enclosing characters in single-quotes ( `''` ) shall preserve the literal value of each character within the single-quotes. A single-quote cannot occur within single-quotes.\n \n ### Exceptions\n If you want your single-quoted string to end in a backslash, you can rewrite as `'string'\\\\` or [[ignore]] this warning.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: This backslash+linefeed is literal. Break outside single quotes if you just want to break the line. [SC1004]"},{"from": "gpt", "value": "## This backslash+linefeed is literal. Break outside single quotes if you just want to break the line.\n \n (This warning was retired after v0.7.2 due to low signal-to-noise ratio)\n \n ### Problematic code:\n \n ```sh\n var='This is long \\\n piece of text'\n ```\n \n ### Correct code:\n \n ```sh\n var='This is a long '\\\n 'piece of text'\n ```\n ### Rationale:\n \n You have a single-quoted string containing a backslash followed by a linefeed (newline). Unlike double-quotes or unquoted strings, this has no special meaning. The string will contain a literal backslash and a linefeed.\n \n If you wanted to break the line but not add a linefeed to the string, stop the single quote, break the line, and reopen it. This is demonstrated in the correct code.\n \n If you wanted to break the line and also include the linefeed as a literal, you don't need a backslash:\n \n ```sh\n var='This is a multi-line string\n with an embedded linefeed'\n ```\n \n \n ### Exceptions:\n \n If you do want a string containing a literal backslash+linefeed combo, such as with `sed`, you can [[ignore]] this warning.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Remove space after `=` if trying to assign a value (or for empty string, use `var=\"\"` ... ). [SC1007]"},{"from": "gpt", "value": "# Remove space after `=` if trying to assign a value (or for empty string, use `var=\"\"` ... ).\n \n ### Problematic code:\n \n ```sh\n # I want programs to show text in Dutch!\n LANGUAGE= nl\n ```\n \n ```sh\n # I want to run the nl command with English error messages!\n LANGUAGE= nl\n ```\n \n ### Correct code:\n \n ```sh\n # I want programs to show text in Dutch!\n LANGUAGE=nl\n ```\n \n ```sh\n # I want to run the nl command with English error messages!\n LANGUAGE='' nl\n ```\n \n ### Rationale:\n \n It's easy to think that `LANGUAGE= nl` would assign `\"nl\"` to the variable `LANGUAGE`. It doesn't.\n \n Instead, it runs `nl` (the \"number lines\" command) and sets `LANGUAGE` to an empty string in its environment.\n \n Since trying to assign values this way is a common mistake, ShellCheck warns about it and asks you to be explicit when assigning empty strings (except for `IFS`, due to the common `IFS= read ..` idiom).\n \n ### Exceptions\n If you're familiar with this behavior and feel that the explicit version is unnecessary, you can [[ignore]] it.\n \n ### Related Resources:\n https://www.gnu.org/software/bash/manual/html_node/Shell-Parameters.html\n https://mywiki.wooledge.org/BashPitfalls#foo_.3D_bar\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: This shebang was unrecognized. ShellCheck only supports sh/bash/dash/ksh. Add a 'shell' directive to specify. [SC1008]"},{"from": "gpt", "value": "## This shebang was unrecognized. ShellCheck only supports sh/bash/dash/ksh. Add a 'shell' directive to specify.\n \n ### Problematic code:\n \n ```sh\n #!/bin/mywrapper\n echo \"Hello World\"\n ```\n \n ### Correct code:\n \n ```sh\n #!/bin/mywrapper\n # shellcheck shell=bash\n echo \"Hello World\"\n ```\n \n ### Rationale:\n \n You have specified a shebang that ShellCheck doesn't recognize. This can be due to invoking the script via a wrapper, specifying a dummy like `#!/bin/false` to prevent execution, or trying to check a script for a non-Bourne shell or tool.\n \n If this really is a sh/bash/dash/ksh script, please add a `shell` directive after the shebang to tell ShellCheck how to interpret the script, as in the example. You can also specify the shell with the `-s` flag. \n \n If this is a script in some other language, like `#!/bin/sed` for a `sed` script, then sorry -- ShellCheck does not support `sed`, `awk`, `expect` scripts. It only supports Bourne style shell scripts. \n \n ### Exceptions:\n \n None.\n \n ### Related Resources:\n \n https://www.gnu.org/software/bash/manual/html_node/Shell-Scripts.html\n https://mywiki.wooledge.org/BashProgramming?highlight=%28shebang%29#Shebang\n https://www.gnu.org/software/gawk/manual/html_node/Executable-Scripts.html\n https://mywiki.wooledge.org/BashPitfalls#On_UTF-8_and_Byte-Order_Marks_.28BOM.29\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: The mentioned parser error was in ... [SC1009]"},{"from": "gpt", "value": "# The mentioned parser error was in ...\n \n This info warning points to the start of what ShellCheck was parsing when it failed. See [[[Parser error]]](https://www.shellcheck.net/wiki/Parser-error) for example and information.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Use semicolon or linefeed before `done` (or quote to make it literal). [SC1010]"},{"from": "gpt", "value": "## Use semicolon or linefeed before `done` (or quote to make it literal).\n \n (or `do` `then`, `fi`, `esac`)\n \n ### Problematic code:\n \n ```sh\n for f in *; do echo \"$f\" done\n ```\n or\n \n ```sh\n echo $f is done\n ```\n \n ### Correct code:\n \n ```sh\n for f in *; do echo \"$f\"; done\n ```\n \n or\n \n ```sh\n echo \"$f is done\"\n ```\n \n \n ### Rationale:\n \n ShellCheck found a keyword like `done`, `then`, `fi`, `esac`, etc used as the argument of a command. This means that the shell will interpret it as a literal string rather than a shell keyword. To be interpreted as a keyword, it must be the first word in the line (i.e. after `;`, `&` or a linefeed). \n \n In the example, `echo \"$f\" done` is the same as `echo \"$f\" \"done\"`, and the `done` does not terminate the loop. This is fixed by terminating the `echo` command with a `;` so that the `done` is the first word in the next line.\n \n ### Exceptions\n \n If you're intentionally using `done` as a literal, you can quote it to make this clear to ShellCheck (and also human readers), e.g. instead of `echo Task is done`, use `echo \"Task is done\"`. This makes no difference to the shell, but it will silence this warning.\n \n From POSIX-2018, section \"C.2.10 Shell Grammar,\" regarding the syntax, `if (false) then (echo x) else (echo y) fi`:\n https://pubs.opengroup.org/onlinepubs/9699919799/xrat/V4_xcu_chap02.html#tag_23_02_10\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: This apostrophe terminated the single quoted string! [SC1011]"},{"from": "gpt", "value": "## This apostrophe terminated the single quoted string!\n \n ### Problematic code:\n \n ```sh\n echo 'Nothing so needs reforming as other peoples' habits.'\n ```\n \n ### Correct code:\n \n ```sh\n echo 'Nothing so needs reforming as other peoples'\\'' habits.'\n ```\n or\n ```sh\n echo \"Nothing so needs reforming as other peoples' habits.\"\n ```\n ### Rationale:\n \n When writing a string in single-quotes, you have to make sure that any apostrophes in the text don't accidentally terminate the single-quoted string prematurely.\n \n Escape them properly (see the correct code) or switch quotes to avoid the problem.\n \n \n ### Additional options:\n ```sh\n echo '...peoples\\ habits.'\n ...peoples\\ habits.\n ```\n ```sh\n $ echo $'...peoples\\x27 habits.'\n ...peoples' habits.\n ```\n \n \n ### Exceptions:\n \n None.\n \n \n ### Related Resources:\n https://www.gnu.org/software/bash/manual/html_node/Quoting.html\n \n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: `\\t` is just literal `t` here. For tab, use `\"$(printf '\\t')\"` instead. [SC1012]"},{"from": "gpt", "value": "## `\\t` is just literal `t` here. For tab, use `\"$(printf '\\t')\"` instead.\n \n ### Problematic code:\n \n ```sh\n # Want tab\n $ var=foo\\tbar\n $ printf '<%s>\\n' \"$var\"\n \n \n $ var=foo\\\\tbar\n $ printf '<%s>\\n' \"$var\"\n \n \n ```\n \n or\n \n ```sh\n # Want newline\n $ var=foo\\nbar\n $ printf '<%s>\\n' \"$var\"\n \n \n $ var=foo\\\\nbar\n $ printf '<%s>\\n' \"$var\"\n \n ```\n \n \n ### Correct code:\n \n ```sh\n $ var=\"foo$(printf '\\t')bar\" # As suggested in warning\n $ printf '<%s>\\n' \"$var\"\n \n \n $ var=\"$(printf 'foo\\tbar')\" # Equivalent alternative\n $ printf '<%s>\\n' \"$var\"\n \n ```\n \n or\n \n ```sh\n $ # Literal, quoted newline\n $ line=\"foo\n > bar\"\n $ printf '<%s>\\n' \"$line\"\n \n ```\n \n or\n \n ```sh\n $ # Newline using ANSI-C quoting\n $ line=$'foo\\nbar'\n $ printf '<%s>\\n' \"$line\"\n \n ```\n \n \n ### Rationale:\n \n ShellCheck has found a `\\t`, `\\n` or `\\r` in a context where they just become regular letters `t`, `n` or `r`. Most likely, it was intended as a tab, newline or carriage return.\n \n To generate such characters (plus other less common ones including `\\a`, `\\f` and octal escapes) , use `printf` as in the example. The exception is for newliness that would be stripped by command substitution; in these cases, use a literal quoted newline instead.\n \n Other characters like `\\z` generate a [[SC1001]] info message, as the intent is less certain.\n \n \n ### Exceptions:\n \n None.\n \n \n ### Related Resources:\n https://www.gnu.org/software/bash/manual/html_node/Bash-Builtins.html#index-printf\n https://pubs.opengroup.org/onlinepubs/9799919799/utilities/printf.html\n https://www.gnu.org/software/bash/manual/html_node/ANSI_002dC-Quoting.html\n \n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Use `if cmd; then ..` to check exit code, or `if [ \"$(cmd)\" = .. ]` to check output. [SC1014]"},{"from": "gpt", "value": "## Use `if cmd; then ..` to check exit code, or `if [ \"$(cmd)\" = .. ]` to check output.\n \n ### Problematic code:\n ```sh\n # WRONG\n if [ grep -q pattern file ]\n then\n echo \"Found a match\"\n fi\n ```\n \n ```sh\n # WRONG\n if ! [[ logname == $LOGNAME ]]\n then\n echo \"Possible `su` shell\"\n fi\n ```\n \n \n ### Correct code:\n ```sh\n if grep -q pattern file\n then\n echo \"Found a match\"\n fi\n ```\n \n ```sh\n if ! [[ $(logname) == $LOGNAME ]]\n then\n echo \"Possible `su` shell\"\n fi\n ```\n \n \n ### Rationale:\n `[ ... ]` as shell syntax is a simple command that tests for whether certain conditions are true or false, such as whether the value assigned to a variable has a non-zero length (`[ -n \"${foo}\" ]`) or whether a file system object is a directory (`[ -d \"${dir}\" ]`). `If-then-(elif-then)-else-fi` statements are logical constructs which themselves contain lists of commands which can include simple commands. \n \n `[` is just regular command, like `whoami` or `grep`, but with a funny name (see `ls -l /bin/[`). It's a shorthand for `test`. `[[` is similar to both `[` and `test`, but `[[` offers some additional unary operators, such as '=~' the regular expression comparison operator. It allows one to use extglobs such as `@(foo|bar)` (a \"bashism\"), among some other less commonly used features. \n \n `[[`, `[` and `test` are often used within `if...fi` constructs in the conditional commands position: which is between the 'if' and the 'then.' \n \n There are certain shell syntaxes which can be wrapped **directly** around simple commands, in particular:\n - (1) `{ ...;}`, group commands, \n - (2) `$( ... )`, command substitutions, \n - (3) `<( ... )` and `>( ... )`, process substitutions, \n - (4) `( ... )`, subshells, and\n - (5) `$(( ... ))` and `(( ... ))`, arithmetic evaluations.\n \n Some examples include: \n - (1) `{ echo {a..z}; echo {0..9};} > ~/f`, \n - (2) `[[ $(logname) == $LOGNAME ]]`, \n - (3) `readarray -t files < <( find ...)`,\n - (4) `(cd /foo || exit 1; tar ...)`, and\n - (5) `dd bs=$((2**12)) count=1 if=/dev/zero of=/tmp/zeroed-block`, respectively. \n \n Note how in example (2) `logname` is enclosed **directly** within a command substitution, which is itself enclosed within a `[[` reserved word / conditional expression / compound command. \n \n If you want to check the exit status of a certain command, use that command directly as demonstrated in the correct code, above.\n \n If you want to check the output of a command, use `\"$(..)\"` to get its output, and then use `test`/`[` or `[[` to do a string comparison:\n \n ```sh\n # Check output of `whoami` against the string `root`\n if [ \"$(whoami)\" = \"root\" ]\n then\n echo \"Running as root\"\n fi\n ```\n \n \n ### Exceptions:\n \n None.\n \n \n ### Related Resources:\n \n For more information, see [this problem in the Bash Pitfall](http://mywiki.wooledge.org/BashPitfalls#if_.5Bgrep_foo_myfile.5D) list, or generally [Tests and Conditionals](http://mywiki.wooledge.org/BashGuide/TestsAndConditionals) in the wooledge.org BashGuide \n \n * [How do I use a file grep comparison inside a bash if/else statement?](https://stackoverflow.com/questions/2480584/how-do-i-use-a-file-grep-comparison-inside-a-bash-if-else-statement)\n * [Bash Pitfalls: `if [grep foo myfile]`](https://mywiki.wooledge.org/BashPitfalls#if_.5Bgrep_foo_myfile.5D)\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: This is a Unicode double quote. Delete and retype it. [SC1015]"},{"from": "gpt", "value": "## This is a Unicode double quote. Delete and retype it.\n \n ### Problematic code:\n \n ```sh\n echo “hello world”\n ```\n \n ### Correct code:\n \n ```sh\n echo \"hello world\"\n ```\n \n ### Rationale:\n \n Blog software and word processors frequently replaces ASCII quotes `\"\"` with fancy Unicode quotes, `“”`. To Bash, Unicode quotes are considered regular literals and not quotes at all.\n \n Simply delete them and retype them in your editor.\n \n ### Status:\n \n This error was retired after 0.4.5. In this version and earlier, ShellCheck parsed slanted quotes as a valid double quote. This meant that the warning could not simply be ignored. It has since been replaced by [[SC1110]] (outside quotes) and [[SC1111]] (inside double-quotes).\n \n ### Exceptions\n \n If you really want literal Unicode double quotes, you can put them in single-quotes (or Unicode single-quotes in double-quotes) to make ShellCheck ignore them, e.g.,\n \n ```sh\n printf 'Warning: “wakeonlan” is not installed.\\n'\n ```\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: This is a Unicode single quote. Delete and retype it. [SC1016]"},{"from": "gpt", "value": "## This is a Unicode single quote. Delete and retype it.\n \n ### Problematic code:\n \n ```sh\n echo ‘hello world’\n ```\n \n ### Correct code:\n \n ```sh\n echo 'hello world'\n ```\n \n ### Rationale:\n \n Some software, like macOS, Microsoft Word, and WordPress, may automatically replace your regular quotes with slanted Unicode quotes. Try deleting and retyping them, and/or disable “smart quotes” in your editor or OS.\n \n ### Status:\n \n This error was retired after 0.4.5. In this version and earlier, ShellCheck parsed slanted quotes as a valid double-quote. This meant that the warning could not simply be ignored. It has since been replaced by [[SC1110]] (outside quotes) and [[SC1112]] (inside single-quotes).\n \n \n ### Exceptions\n \n If you want to use typographic single-quotes, you can put them in double-quotes (or typographic double-quotes in single-quotes) to make ShellCheck ignore them, e.g.,\n \n ```sh\n printf \"Warning: ‘wakeonlan’ is not installed.\\n\"\n ```\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Literal carriage return. Run script through `tr -d '\\r'` . [SC1017]"},{"from": "gpt", "value": "## Literal carriage return. Run script through `tr -d '\\r'` .\n \n ### Problematic code:\n \n ```console\n $ cat -v myscript\n #!/bin/sh^M\n echo \"Hello World\"^M\n ```\n \n ### Correct code:\n \n ```console\n $ cat -v myscript\n #!/bin/sh\n echo \"Hello World\"\n ```\n \n ### Rationale:\n \n The script uses Windows/MS-DOS style `\\r\\n` line terminators instead of Unix-style `\\n` terminators. The additional `\\r` aka `^M` aka carriage return characters will be treated literally, and results in all sorts strange bugs and messages.\n \n You can verify this with `cat -v yourfile` and see whether or not each line ends with a `^M`. To delete them, open the file in your editor and save the file as \"Unix\", \"Unix/macOS Format\", `:set ff=unix` or similar if it supports it.\n \n If you don't know how to get your editor to save a file with Unix line terminators, you can use `tr`:\n \n ```sh\n tr -d '\\r' < badscript > goodscript\n # or\n dos2unix badscript\n ```\n \n This will read a script `badscript` with possible carriage returns, and write `goodscript` without them.\n \n ### Exceptions:\n \n None\n \n ### Related resources:\n \n * [BashFaq: How do I convert a file from MS-DOS format to Unix format (remove CRs from CR-LF line terminators)?](https://mywiki.wooledge.org/BashFAQ/052)\n * [StackOverflow: Are shell-scripts sensitive to encoding and line-endings?](https://stackoverflow.com/questions/39527571/are-shell-scripts-sensitive-to-encoding-and-line-endings)\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: This is a Unicode non-breaking space. Delete it and retype as space. [SC1018]"},{"from": "gpt", "value": "# This is a Unicode non-breaking space. Delete it and retype as space.\n \n You copy-pasted some code, probably from a blog or web site, which for formatting reasons contained Unicode no-break spaces or Unicode zero-width spaces instead of regular spaces or in words.\n \n To humans, a zero-width space is invisible and a non-breaking space is indistinguishable from a regular space, but the shell does not agree.\n \n If you have just a few, delete the indicated space/word and retype it. If you have tons, do a search-and-replace in your editor (copy-paste an offending space into the search field, and type a regular space into the replace field), or use the following command to remove them:\n \n ```sh\n sed -e $'s/\\xC2\\xA0/ /g' -e $'s/\\xE2\\x80\\x8b//g' -i yourfile\n ```\n \n On macOS, a non-breaking space can be inserted into most programs by holding ⌥ Option+Space.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Expected this to be an argument to the unary condition. [SC1019]"},{"from": "gpt", "value": "## Expected this to be an argument to the unary condition.\n \n ### Problematic code:\n \n ```sh\n [ -x ]\n ```\n \n ### Correct code:\n \n ```sh\n [ -x \"myfile\" ]\n ```\n ### Rationale:\n \n ShellCheck has found a unary test operator that does not appear to be followed by a valid shell word. \n \n This could be because of a misplaced `]`, `)`, or a missing space before the `]`.\n \n Check the syntax, make sure the test operator has an operand, and try again.\n \n ### Exceptions:\n \n None.\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: You need a space before the `]` or `]]` [SC1020]"},{"from": "gpt", "value": "## You need a space before the `]` or `]]`\n \n ### Problematic code:\n \n ```sh\n if [ \"$STUFF\" = \"\"]; then\n ```\n \n ### Correct code:\n \n ```sh\n if [ \"$STUFF\" = \"\" ]; then\n ```\n \n ### Rationale:\n Bourne shells are very whitespace sensitive. Adding or removing spaces can drastically alter the meaning of a script. In these cases, ShellCheck has noticed that you're missing a space at the position indicated.\n \n ### Exceptions\n None.\n \n ### Ignore\n ```sh\n # shellcheck disable=SC1020\n if [ \"$STUFF\" = \"\"]; then\n ```\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: If grouping expressions inside `[[..]]`, use `( .. )`. [SC1026]"},{"from": "gpt", "value": "## If grouping expressions inside `[[..]]`, use `( .. )`.\n \n ### Problematic code:\n \n ```sh\n [[ [ a || b ] && c ]]\n [ [ a -o b ] -a c ]]\n ```\n \n ### Correct code:\n \n ```sh\n [[ ( a || b ) && c ]]\n [ \\( a -o b \\) -a c ]] # or { [ a ] || [ b ]; } && [ c ]\n ```\n ### Rationale:\n \n `[ .. ]` should not be used to group subexpressions inside `[[ .. ]]` or `[ .. ]` statements.\n \n For `[[ .. ]]`, use regular parentheses.\n \n For `[ .. ]`, either use escaped parentheses, or preferably rewrite the expression into multiple `[ .. ]` joined with `&&`, `||` and `{ ..; }` groups. The latter is preferred because `[ .. ]` is undefined for more than 4 arguments in POSIX.\n \n ### Exceptions:\n \n None\n \n ### Related resources:\n \n * [Bash Pitfalls: `if [ [ a = b ] && [ c = d ] ]; then ...`](https://mywiki.wooledge.org/BashPitfalls#pf11)\n * [POSIX `test`](http://pubs.opengroup.org/onlinepubs/9699919799/utilities/test.html)\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Expected another argument for this operator. [SC1027]"},{"from": "gpt", "value": "## Expected another argument for this operator.\n \n ### Problematic code:\n \n ```sh\n [ $a -ne ]\n ```\n \n ### Correct code:\n \n ```sh\n [ $a -ne $b ]\n ```\n ### Rationale:\n \n ShellCheck found a `test` operator without an operand. This could be a copy-paste fail, bad linebreak, or trying to use `<>` instead of `!=` or `-ne`. \n \n ### Exceptions:\n \n None.\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: In `[..]` you have to escape `\\( \\)` or preferably combine `[..]` expressions. [SC1028]"},{"from": "gpt", "value": "## In `[..]` you have to escape `\\( \\)` or preferably combine `[..]` expressions.\n \n ### Problematic code:\n \n ```sh\n [ -e ~/.bashrc -a ( -x /bin/dash -o -x /bin/ash ) ]\n ```\n \n ### Correct code:\n \n In POSIX:\n ```sh\n [ -e ~/.bashrc ] && { [ -x /bin/dash ] || [ -x /bin/ash ]; }\n ```\n \n Obsolete XSI syntax:\n ```sh\n [ -e ~/.bashrc -a \\( -x /bin/dash -o -x /bin/ash \\) ]\n ```\n \n ### Rationale:\n \n `[` is implemented as a regular command, so `(` is not special.\n \n The preferred way is not to group inside `[ .. ]` and instead compose multiple `[ .. ]` statments using the shell's `&&`, `||` and `{ ..; }` syntax, since this is well defined by POSIX.\n \n Some shells, such as Bash, support grouping with `\\( .. \\)`, but this is an obsolete XSI-only extension.\n \n ### Exceptions:\n \n None\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: In `[[..]]` you shouldn't escape `(` or `)`. [SC1029]"},{"from": "gpt", "value": "## In `[[..]]` you shouldn't escape `(` or `)`.\n \n ### Problematic code:\n \n ```sh\n [[ -e ~/.bashrc && \\( -x /bin/dash || -x /bin/ash \\) ]]\n ```\n \n ### Correct code:\n \n ```sh\n [[ -e ~/.bashrc && ( -x /bin/dash || -x /bin/ash ) ]]\n ```\n \n ### Rationale:\n \n You don't have to -- and can't -- escape `(` or `)` inside a `[[ .. ]]` expression like you do in `[ .. ]`. Just remove the escaping.\n \n ### Exceptions:\n \n None.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Test expression was opened with double `[[` but closed with single `]`. Make sure they match. [SC1033]"},{"from": "gpt", "value": "## Test expression was opened with double `[[` but closed with single `]`. Make sure they match.\n \n (or [[SC1034]] for vice versa)\n \n ### Problematic code:\n \n ```sh\n [[ -z \"$var\" ]\n ```\n \n ### Correct code:\n \n ```sh\n [[ -z \"$var\" ]]\n ```\n \n ### Rationale:\n \n ShellCheck found a test expression `[ ... ]` (POSIX) or `[[ ... ]]` (ksh/bash), but where the opening and closing brackets did not match (i.e. `[[ .. ]` or `[ .. ]]`). The brackets need to match up to work.\n \n Note in particular that `[..]` do *not* work like parentheses in other languages. You can not do:\n \n ```sh\n # Invalid\n [[ x ] || [ y ]]\n ```\n You would instead use two separate test expressions joined by `||`:\n \n ```sh\n # Valid basic test expressions (sh/bash/ksh)\n [ x ] || [ y ]\n \n # Valid extended test expressions (bash/ksh)\n [[ x ]] || [[ y ]]\n ```\n \n ### Exceptions:\n \n None\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Test expression was opened with double `[` but closed with single `]]`. Make sure they match. [SC1034]"},{"from": "gpt", "value": "## Test expression was opened with double `[` but closed with single `]]`. Make sure they match.\n See similar error [[SC1033]]\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: You need a space here [SC1035]"},{"from": "gpt", "value": "## You need a space here\n \n ### Problematic code:\n \n ```sh\n if ![-z foo ]; then true; fi # if command `[-z' w/ args `foo', `]' fails..\n ```\n ### Correct code:\n \n ```sh\n if ! [ -z foo ]; then true; fi # if command `[' w/ args `-z', `foo', `]' fails..\n ```\n \n ### Rationale:\n \n Bourne shells are very whitespace sensitive. Adding or removing spaces can drastically alter the meaning of a script. In these cases, ShellCheck has noticed that you're missing a space at the position indicated.\n \n ### Exceptions\n \n ShellCheck does not understand [Bash History Expansion](https://www.gnu.org/software/bash/manual/html_node/History-Interaction.html), an interactive shell feature also using `!` (such as `!!` to expand to the previous command). \n \n These features are disabled by default in shells and very rarely used in scripts, but may occasionally be found in interactively sourced files like `.bashrc`. Please ignore the error in these cases.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: `(` is invalid here. Did you forget to escape it? [SC1036]"},{"from": "gpt", "value": "## `(` is invalid here. Did you forget to escape it?\n \n ### Problematic code:\n \n ```sh\n echo (foo) bar\n ```\n \n ### Correct code:\n \n Depends on your intention:\n \n ```sh\n echo \"(foo) bar\" # Literal parentheses\n echo \"$(foo) bar\" # Command expansion\n echo \"foo bar\" # Tried to use parentheses for grouping or function invocation\n ```\n \n ### Rationale:\n \n ShellCheck expected an ordinary shell word but found an opening parenthesis instead.\n \n Determine what you intended the parenthesis to do and rewrite accordingly. Common issues include:\n \n * Wanting them to be literal, as in `echo (FAIL) Some tests failed`. In this case, it requires quoting.\n * Wanting command expansion, as in `echo Today is (date)`. Add the missing `$`: `echo \"Today is $(date)\"`\n * Adding parentheses because other languages need them in that context, such as `foo (bar, 42)` to call a function. This should be `foo bar 42`. Also, shells do not support tuples or passing arrays as single parameters.\n \n ### Exceptions:\n \n Bash allows some parentheses as part of assignment-like tokens to certain commands, including `export` and `eval`. This is a workaround in Bash to allow commands that normally would not be valid:\n \n ```sh\n eval foo=(bar) # Valid command\n echo foo=(bar) # Invalid syntax\n f=foo; eval $f=(bar) # Also invalid\n ```\n \n In these cases, please quote the command, such as `eval \"foo=(bar)\"`. This does not change the behavior, but stops relying on Bash-specific parsing quirks.\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Braces are required for positionals over 9, e.g. `${10}`. [SC1037]"},{"from": "gpt", "value": "## Braces are required for positionals over 9, e.g. `${10}`.\n \n ### Problematic code:\n \n ```sh\n echo \"Ninth parameter: $9\"\n echo \"Tenth parameter: $10\"\n ```\n \n ### Correct code:\n \n ```sh\n echo \"Ninth parameter: $9\"\n echo \"Tenth parameter: ${10}\"\n ```\n \n ### Rationale:\n \n For legacy reasons, `$10` is interpreted as the variable `$1` followed by the literal string `0`.\n \n Curly braces are needed to tell the shell that both digits are part of the parameter expansion.\n \n ### Exceptions\n \n If you wanted the trailing digits to be literal, `${1}0` will make this clear to both humans and ShellCheck.\n \n In `dash`, `$10` is ([wrongly](https://gnu.org/s/autoconf/manual/html_node/Shell-Substitutions.html)) interpreted as `${10}`, so some 'reversed' care should also be taken:\n \n ```sh\n bash -c 'set a b c d e f g h i j; echo $10 ${1}0' # POSIX: a0 a0\n dash -c 'set a b c d e f g h i j; echo $10 ${1}0' # WRONG: j a0\n ```\n \n ### Related resources:\n \n * [BashFaq: How can I access positional parameters after $9?](https://mywiki.wooledge.org/BashFAQ/025)\n * [StackOverflow: How to handle more than 10 parameters in shell](https://stackoverflow.com/q/4912733)\n * [Autoconf Manual: Shell Substitutions](https://www.gnu.org/savannah-checkouts/gnu/autoconf/manual/html_node/Shell-Substitutions.html) - documents some non-POSIX older shells too\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Shells are space sensitive. Use `< <(cmd)`, not `<<(cmd)`. [SC1038]"},{"from": "gpt", "value": "## Shells are space sensitive. Use `< <(cmd)`, not `<<(cmd)`.\n \n ### Problematic code:\n \n ```sh\n while IFS= read -r line\n do\n printf \"%q\\n\" \"$line\"\n done <<(curl -s http://example.com)\n ```\n \n ### Correct code:\n \n ```sh\n while IFS= read -r line\n do\n printf \"%q\\n\" \"$line\"\n done < <(curl -s http://example.com)\n ```\n \n ### Rationale:\n \n You are using `<<(` which is an invalid construct.\n \n You probably meant to redirect `<` from process substitution `<(..)` instead. To do this, a space is needed between the `<` and `<(..)`, i.e. `< <(cmd)`.\n \n ### Exceptions:\n \n None.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Remove indentation before end token (or use `<<-` and indent with tabs). [SC1039]"},{"from": "gpt", "value": "## Remove indentation before end token (or use `<<-` and indent with tabs).\n \n ### Problematic code:\n \n ```sh\n for f in *.png\n do\n cat << HTML\n
\n HTML\n done > index.html\n ```\n \n ### Correct code:\n \n ```sh\n for f in *.png\n do\n cat << HTML\n
\n HTML\n done > index.html\n ```\n \n ### Rationale:\n \n The here document delimiter will not be recognized if it is indented.\n \n You can fix it in one of two ways:\n \n 1. Simply remove the indentation, even though this may break formatting.\n 2. Use `<<-` instead of `<<`, and indent the script with tabs only (spaces will not be recognized).\n \n Removing the indentation is preferred, since the script won't suddenly break if it's reformatted, copy-pasted, or saved with a different editor.\n \n ### Exceptions:\n \n If the line was supposed to be a literal part of the here document, consider choosing a less ambiguous token.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: When using `<<-`, you can only indent with tabs. [SC1040]"},{"from": "gpt", "value": "## When using `<<-`, you can only indent with tabs.\n \n ### Problematic code:\n \n Any code using `<<-` that is indented with spaces. `cat -T script` shows\n \n ```sh\n cat <<- foo\n Hello world\n foo\n ```\n \n ### Correct code:\n \n Code using `<<-` must be indented with tabs. `cat -T script` shows\n \n ```sh\n ^Icat <<- foo\n ^I^IHello world\n ^Ifoo\n ```\n \n Or simply don't indent the end token:\n \n ```sh\n cat <<- foo\n Hello World\n foo\n ```\n \n ### Rationale:\n \n `<<-`, by design, only strips tabs. Not spaces.\n \n Your editor may be automatically replacing tabs with spaces, either when you type them or when you save the file or both. If you're unable to make it stop, just don't indent the end token.\n \n ### Exceptions\n \n None. But note that copy-pasting code to [shellcheck.net](http://www.shellcheck.net) may also turn correct tabs into spaces on some OS.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Found `eof` further down, but not on a separate line. [SC1041]"},{"from": "gpt", "value": "## Found `eof` further down, but not on a separate line.\n \n Close matches include '-eof' (!= 'eof').\n \n ### Problematic code:\n \n ```sh\n cat <<-eof\n Hello World\n -eof\n ```\n \n ### Correct code:\n \n ```sh\n cat <<- eof\n Hello World\n eof\n ```\n ### Rationale:\n \n Your here document isn't properly terminated.\n \n There is a line containing the terminator you've chosen, but it's not by itself on a separate line.\n \n In the example code, the script uses `<<-eof`, which is the operator `<<-` followed by `eof`. The script therefore looks for `eof` and skips right past the intended terminator because it starts with a dash.\n \n You will get some companion [[SC1042]] errors mentioning lines that contain the string as a substring, though they all point to the start of the here document and not the relevant line:\n \n ```\n In foo line 4:\n Hello\n ^-- SC1041: Found 'eof' further down, but not on a separate line.\n ^-- SC1042: Close matches include '-eof' (!= 'eof').\n ```\n \n Look at your here document and see which line was supposed to terminate it. Then ensure it matches the token exactly, and that it's on its own line with no text before or after.\n \n Under Windows the error might occur due to the standard CRLF line-ending, which is Windows-specific.\n Try to change the line ending into LF.\n \n ### Exceptions:\n \n None.\n \n ---\n Note that SC1041 and [[SC1042]] swapped numbers after v0.4.6 to improve the display order. This rare instance of number reuse was justified by them always occurring together on the same line.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Found EOF further down, but with wrong casing. [SC1043]"},{"from": "gpt", "value": "## Found EOF further down, but with wrong casing.\n \n ### Problematic code:\n \n ```sh\n cat << EOF\n Hello World\n Eof\n ```\n \n ### Correct code:\n \n ```sh\n cat << EOF\n Hello World\n EOF\n ```\n ### Rationale:\n \n ShellCheck found a here document (`<<`) where the end token is missing. However, the end token appears with different case further down. If this was meant to be the end of the here document, make sure the case matches.\n \n ### Exceptions:\n \n None. This error is only emitted when the here document is incomplete.\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Couldn't find end token `EOF` in the here document. [SC1044]"},{"from": "gpt", "value": "## Couldn't find end token `EOF` in the here document.\n \n ### Problematic code:\n \n ```sh\n cat << EOF\n Hello World\n ```\n \n ### Correct code:\n \n ```sh\n cat << EOF\n Hello World\n EOF\n ```\n ### Rationale:\n \n The `<<` here document (aka heredoc) was not properly terminated. The terminating token needs to be on a separate line without indenting (or indented with tabs only when using `<<-`).\n \n Note that you can not put here documents in one liners. For such use cases, use a `<<<` here string:\n \n ```sh\n cat << EOF hello world EOF # Wrong: data and terminator can not be on the same line\n cat <<< \"hello world\" # Correct\n ```\n \n ### Exceptions:\n \n None\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: It's not `foo &; bar`, just `foo & bar`. [SC1045]"},{"from": "gpt", "value": "# It's not `foo &; bar`, just `foo & bar`.\n \n ### Problematic code:\n \n ```sh\n foo &; bar\n ```\n \n ### Correct code:\n \n ```sh\n foo & bar\n ```\n \n ### Rationale:\n \n Both `&` and `;` terminate the command. You should only use one of them.\n \n \n \n ### Exceptions\n \n None.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Couldn't find `fi` for this `if`. [SC1046]"},{"from": "gpt", "value": "## Couldn't find `fi` for this `if`.\n \n ### Problematic code:\n \n ```sh\n if true\n then\n echo \"True\"\n done\n ```\n \n ### Correct code:\n \n ```sh\n if true\n then\n echo \"True\"\n fi\n ```\n ### Rationale:\n \n ShellCheck has found an `if` statement that does not appear to have a matching terminating `fi`.\n \n This could be because it's missing entirely, or because the `if` statement was incorrectly terminated by a mismatched `done`, `esac`, `)` or similar. A companion warning [[SC1047]] is emitted at the point where ShellCheck expected the `fi`.\n \n Check that the `if` statement is completely and correctly terminated.\n \n ### Exceptions:\n \n None\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Expected `fi` matching previously mentioned `if`. [SC1047]"},{"from": "gpt", "value": "## Expected `fi` matching previously mentioned `if`.\n \n See companion warning [[SC1046]].\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Can't have empty then clauses (use `true` as a no-op). [SC1048]"},{"from": "gpt", "value": "## Can't have empty then clauses (use `true` as a no-op).\n \n ### Problematic code:\n \n ```sh\n if [ -e foo ]\n then\n # TODO: handle this\n fi\n ```\n ### Correct code:\n ```sh\n if [ -e foo ]\n then\n # TODO: handle this\n true\n fi\n \n # Or use the no-op colon operator \":\"\n if [ -e foo ]\n then\n # TODO: handle this\n :\n fi\n ```\n \n ### Rationale:\n \n Shells do not allow empty `then` clauses. They need at least one command (and comments are not commands).\n \n If you want a `then` clause that does nothing, use a dummy command like `true`.\n \n ### Exceptions:\n \n None.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Did you forget the `then` for this `if`? [SC1049]"},{"from": "gpt", "value": "## Did you forget the `then` for this `if`?\n \n ### Problematic code:\n \n ```sh\n if true\n echo \"foo\"\n elif true\n echo \"bar\"\n fi\n ```\n \n ### Correct code:\n \n ```sh\n if true\n then\n echo \"foo\"\n elif true\n then\n echo \"bar\"\n fi\n ```\n \n ### Rationale:\n \n ShellCheck found a parsing error in the script, and determined that it's most likely due to a missing `then` keyword for the `if` or `elif` indicated.\n \n Make sure the `then` is there. \n \n Note that the `then` needs a `;` or linefeed before it. `if true then` is invalid, while `if true; then` is correct.\n \n ### Exceptions:\n \n None\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Expected `then`. [SC1050]"},{"from": "gpt", "value": "## Expected `then`.\n \n ### Problematic code:\n \n ```sh\n if true\n echo \"True\"\n fi\n ```\n \n ### Correct code:\n \n ```sh\n if true\n then\n echo \"True\"\n fi\n ```\n ### Rationale:\n \n ShellCheck has found an `if` statement that appears to be missing a `then`.\n \n Make sure the `then` exists, and that it is the first word of the line (or immediately preceded by a semicolon).\n \n ### Exceptions:\n \n None\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Semicolons directly after `then` are not allowed. Just remove it. [SC1051]"},{"from": "gpt", "value": "## Semicolons directly after `then` are not allowed. Just remove it.\n \n ### Problematic code:\n \n ```sh\n if true; then; echo \"Hi\"; fi\n ```\n \n ### Correct code:\n \n ```sh\n if true; then echo \"Hi\"; fi\n ```\n ### Rationale:\n \n `then` keywords should not be followed by semicolons. It's not valid shell syntax.\n \n You can follow them directly with a line break or another command.\n \n ### Exceptions:\n \n None\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Semicolons directly after `then` are not allowed. Just remove it. [SC1052]"},{"from": "gpt", "value": "## Semicolons directly after `then` are not allowed. Just remove it.\n \n ### Problematic code:\n \n ```sh\n if true; then; echo \"Hi\"; fi\n ```\n \n ### Correct code:\n \n ```sh\n if true; then echo \"Hi\"; fi\n ```\n ### Rationale:\n \n `then` keywords should not be followed by semicolons. It's not valid shell syntax.\n \n You can follow them directly with a line break or another command.\n \n ### Exceptions:\n \n None\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Semicolons directly after `else` are not allowed. Just remove it. [SC1053]"},{"from": "gpt", "value": "## Semicolons directly after `else` are not allowed. Just remove it.\n \n ### Problematic code:\n \n ```sh\n if mycommand; then echo \"True\"; else; echo \"False\"; fi\n ```\n \n ### Correct code:\n \n ```sh\n if mycommand; then echo \"True\"; else echo \"False\"; fi\n ```\n \n ### Rationale:\n \n `else` keywords should not be followed by semicolons. It's not valid shell syntax.\n \n You can follow them directly with a line break or another command.\n \n ### Exceptions:\n \n None\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: You need a space after the `{`. [SC1054]"},{"from": "gpt", "value": "## You need a space after the `{`.\n \n ### Problematic code:\n \n ```sh\n foo() {echo \"hello world\"; }\n ```\n \n ### Correct code:\n \n ```sh\n foo() { echo \"hello world\"; }\n ```\n ### Rationale:\n \n `{` is only recognized as the start of a command group when it's a separate token.\n \n If it's not a separate token, like in the problematic example, it will be considered a literal character, as if writing `\"{echo\"` with quotes, and therefore usually cause a syntax error.\n \n ### Exceptions:\n \n None.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: You need at least one command here. Use `true;` as a no-op. [SC1055]"},{"from": "gpt", "value": "## You need at least one command here. Use `true;` as a no-op.\n \n ### Problematic code:\n \n ```sh\n submitbug() {\n # TODO: Implement me\n }\n ```\n \n ### Correct code:\n \n ```sh\n submitbug() {\n # TODO: Implement me\n true\n }\n ```\n ### Rationale:\n \n ShellCheck found an empty code block. This could be an empty function as shown, a loop with an empty body, or similar.\n \n Sh/bash does not allow empty code blocks. Insert at least one command. If you don't want the block to do anything, `true` (aka `:`) is a good no-op.\n \n ### Exceptions:\n \n None\n \n ### Related resources:\n * [StackOverflow: Why cannot I define an empty function in shell?](https://stackoverflow.com/questions/39307615/why-cannot-i-define-an-empty-function-in-shell)\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Expected a `}`. If you have one, try a `;` or `\\n` in front of it. [SC1056]"},{"from": "gpt", "value": "## Expected a `}`. If you have one, try a `;` or `\\n` in front of it.\n \n ### Problematic code:\n \n ```sh\n #!/bin/bash\n bar() { echo \"hello world\" }\n ```\n \n ### Correct code:\n \n ```sh\n #!/bin/bash\n bar() { echo \"hello world\";}\n ```\n ### Rationale:\n \n `}` is only recognized as the end of a command group when it's a separate token.\n \n If it's not a separate token, like in the problematic example, it will be considered a literal character, as if writing `echo \"foo}\"` with quotes, and therefore usually cause a syntax error.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Did you forget the `do` for this loop? [SC1057]"},{"from": "gpt", "value": "## Did you forget the `do` for this loop?\n \n ### Problematic code:\n \n ```sh\n while read -r line\n echo $line\n done\n ```\n \n ### Correct code:\n \n ```sh\n while read -r line\n do\n echo $line\n done\n ```\n ### Rationale:\n \n ShellCheck found a loop that appears to be missing its `do` statement. Make sure the loop syntax is correct.\n \n ### Exceptions:\n \n None.\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Expected `do`. [SC1058]"},{"from": "gpt", "value": "## Expected `do`.\n \n ### Problematic code:\n \n ```sh\n for file in *\n echo \"$file\"\n done\n ```\n \n ### Correct code:\n \n ```sh\n for file in *\n do\n echo \"$file\"\n done\n ```\n ### Rationale:\n \n ShellCheck has found a loop that appears to be missing a `do` statement. In the problematic code, it was simply forgotten.\n \n Verify that the `do` exists, and that it's in the correct place.\n \n ### Exceptions:\n \n None\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Semicolon is not allowed directly after `do`. You can just delete it. [SC1059]"},{"from": "gpt", "value": "## Semicolon is not allowed directly after `do`. You can just delete it.\n \n ### Problematic code:\n \n ```sh\n while true; do; true; done\n \n while true;\n do;\n true;\n done;\n ```\n \n ### Correct code:\n \n ```sh\n while true; do true; done\n \n while true;\n do\n true;\n done;\n ```\n ### Rationale:\n \n Semicolon `;` is not allowed directly after a `do` keyword. Follow it directly with either a command or a linefeed as shown in the example.\n \n ### Exceptions:\n \n None.\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Can't have empty do clauses (use `true` as a no-op) [SC1060]"},{"from": "gpt", "value": "## Can't have empty do clauses (use `true` as a no-op)\n \n ### Problematic code:\n \n ```sh\n for i in 1 2 3; do\n done\n ```\n \n ### Correct code:\n \n ```sh\n for i in 1 2 3; do\n true\n done\n ```\n \n ### Rationale:\n \n An empty `do ... done` block is not valid.\n Use `true` or `:` if you need no command at all.\n \n ### Exceptions:\n \n None.\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Couldn't find `done` for this `do`. [SC1061]"},{"from": "gpt", "value": "## Couldn't find `done` for this `do`.\n \n ### Problematic code:\n \n ```sh\n yes() {\n while echo \"y\"\n do\n true\n }\n ```\n \n ### Correct code:\n \n ```sh\n yes() {\n while echo \"y\"\n do\n true\n done\n }\n ```\n ### Rationale:\n \n ShellCheck found a `do` without a corresponding `done`.\n \n Double check that the `done` exists, and that it correctly matches the indicated `do`. A companion warning [[SC1062]] is emitted where ShellCheck first noticed it was missing. \n \n ### Exceptions:\n \n None.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Expected `done` matching previously mentioned `do`. [SC1062]"},{"from": "gpt", "value": "## Expected `done` matching previously mentioned `do`.\n \n See companion warning [[SC1061]]\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: You need a line feed or semicolon before the `do`. [SC1063]"},{"from": "gpt", "value": "## You need a line feed or semicolon before the `do`.\n \n ### Problematic code:\n \n ```sh\n for file in * do\n echo \"$file\"\n done\n ```\n \n ### Correct code:\n \n ```sh\n for file in *; do\n echo \"$file\"\n done\n \n # or \n \n for file in *\n do\n echo \"$file\"\n done\n ```\n ### Rationale:\n \n ShellCheck found a `do` on the same line as a loop, but `do` only starts a loop block at the start of a line/statement. Make the `do` the start of a new line/statement by inserting a linefeed or semicolon in front of it.\n \n ### Exceptions:\n \n If you wanted to treat `do` as a literal string, you can quote it to make this clear to ShellCheck and humans:\n \n ```\n for f in \"for\" \"do\" \"done\"\n do\n echo \"Shell keywords include: $f\"\n done\n ```\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Expected a `{` to open the function definition. [SC1064]"},{"from": "gpt", "value": "## Expected a `{` to open the function definition.\n \n ### Problematic code:\n \n ```sh\n foo() {\n echo \"hello world\"\n }\n foo()\n ```\n \n ### Correct code:\n \n ```sh\n foo() {\n echo \"hello world\"\n }\n foo\n ```\n ### Rationale:\n \n ShellCheck found what appears to be the start of a function definition, but without a function body.\n \n One common cause is that you are trying to call a function by appending parentheses, e.g. `foo()` like in C. Bash does not use or allow parentheses after a function name to call it. The function `foo` should be called using just `foo` like in the example. \n \n If you are declaring a function, make sure it looks like the correct code above, and that it does not try to declare any parameters (parameters are instead accessed with `$1` and up). \n \n If you are trying to do something else, look up the syntax for what you are trying to do.\n \n \n ### Exceptions:\n \n POSIX allows the body of a function to be any compound command, e.g. `foo() for i; do :; done`. Since this usage is rare, ShellCheck intentionally requires the body to be `{ ..; }` (or `( ..; )`):\n \n ```sh\n foo() {\n for i; do :; done\n }\n ```\n \n This additional structure requirement helps improve error messages and suggestions by not parsing down a path that less advanced users wouldn't expect.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Trying to declare parameters? Don't. Use `()` and refer to params as `$1`, `$2`, … [SC1065]"},{"from": "gpt", "value": "## Trying to declare parameters? Don't. Use `()` and refer to params as `$1`, `$2`, …\n \n ### Problematic code:\n \n ```sh\n foo(input) {\n echo \"$input\"\n }\n foo(\"hello world\");\n ```\n \n ### Correct code:\n \n ```sh\n foo() {\n echo \"$1\"\n }\n foo \"hello world\"\n ```\n \n ### Rationale:\n \n Shell script functions behave just like scripts and other commands:\n \n - They always take a 0 to N parameters, referred to with `$1`, `$2` etc. They can not declare parameters by name.\n - They are executed using `name arg1 arg2`, and not with parentheses as C-like languages.\n \n ### Exceptions:\n \n None.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Don't use `$` on the left side of assignments. [SC1066]"},{"from": "gpt", "value": "## Don't use `$` on the left side of assignments.\n \n ### Problematic code:\n \n ```sh\n $greeting=\"Hello World\"\n ```\n \n ### Correct code:\n \n ```sh\n greeting=\"Hello World\"\n ```\n \n Alternatively, if the goal was to assign to a variable whose name is in another variable (indirection), use `declare`:\n \n ```sh\n name=foo\n declare \"$name=hello world\"\n echo \"$foo\"\n ```\n \n Or if you actually wanted to compare the value, use a test expression:\n \n ```sh\n if [ \"$greeting\" = \"hello world\" ]\n then\n echo \"Programmer, I presume?\"\n fi\n ```\n \n ### Rationale:\n \n Unlike Perl or PHP, `$` is not used when assigning to a variable.\n \n ### Exceptions\n \n None.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: For indirection, use arrays, `declare \"var$n=value\"`, or (for sh) `read`/`eval` [SC1067]"},{"from": "gpt", "value": "## For indirection, use arrays, `declare \"var$n=value\"`, or (for sh) `read`/`eval`\n \n Note: Removed in [v0.7.2 - 2021-04-20](https://github.com/koalaman/shellcheck/commit/fbb14d6b384a65ee16781966d9d240db9ed7b644)\n \n ### Problematic code:\n \n ```sh\n n=1\n var$n=\"hello\"\n ```\n \n ### Correct code:\n \n For integer indexing in ksh/bash, consider using an indexed array:\n \n ```sh\n n=1\n var[n]=\"hello\"\n echo \"${var[n]}\"\n ```\n \n For string indexing in ksh/bash, use an associative array:\n \n ```sh\n typeset -A var\n n=\"greeting\"\n var[$n]=\"hello\"\n echo \"${var[$n]}\"\n ```\n \n If you actually need a variable with the constructed name in bash, use `declare`:\n \n ```sh\n n=\"Foo\"\n declare \"var$n=42\"\n echo \"$varFoo\"\n ```\n \n For `sh`, with single line contents, consider `read`:\n ```sh\n n=\"Foo\"\n read -r \"var$n\" << EOF\n hello\n EOF\n echo \"$varFoo\"\n ```\n \n or with careful escaping, `eval`:\n \n ```sh\n n=Foo\n eval \"var$n='hello'\"\n echo \"$varFoo\"\n ```\n \n ### Rationale:\n \n `var$n=value` is not a valid way of assigning to a dynamically created variable name in any shell. Please use one of the other methods to assign to names via expanded strings. [Wooledge BashFaq #6](https://mywiki.wooledge.org/BashFAQ/006) has significantly more information on the subject.\n \n \n ### Exceptions:\n \n None\n \n ### Related resources:\n \n * [Wooledge BashFaq #6](https://mywiki.wooledge.org/BashFAQ/006): How can I use variable variables (indirect variables, pointers, references) or associative arrays?\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Don't put spaces around the `=` in assignments. [SC1068]"},{"from": "gpt", "value": "# Don't put spaces around the `=` in assignments.\n \n Note: Removed in [v0.7.2 - 2021-04-20](https://github.com/koalaman/shellcheck/commit/fbb14d6b384a65ee16781966d9d240db9ed7b644)\n \n ### Problematic code:\n \n ```sh\n foo = 42\n ```\n \n ### Correct code:\n \n ```sh\n foo=42\n ```\n \n ### Rationale:\n \n Shells are space sensitive. `foo=42` means to assign `42` to the variable `foo`. `foo = 42` means to run a command named `foo`, and pass `=` as `$1` and `42` as `$2`.\n \n ### Exceptions\n \n If you actually wanted to run a command named foo and provide `=` as the first argument, simply quote it to make ShellCheck be quiet: `foo \"=\" 42`.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: You need a space before the `[`. [SC1069]"},{"from": "gpt", "value": "## You need a space before the `[`.\n \n ### Problematic code:\n \n ```sh\n if[ -e file ]\n then echo \"exists\"; fi\n ```\n \n ### Correct code:\n \n ```sh\n if [ -e file ]\n then echo \"exists\"; fi\n ```\n ### Rationale:\n \n ShellCheck found a keyword immediately followed by a `[`. There needs to be a space between them.\n \n ### Exceptions:\n \n None\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Parsing stopped here. Mismatched keywords or invalid parentheses? [SC1070]"},{"from": "gpt", "value": "## Parsing stopped here. Mismatched keywords or invalid parentheses?\n \n ### Rationale\n \n ShellCheck found a syntax error at the indicated location. Barring a bug in ShellCheck itself, your shell will also crash with a syntax error at the same location, so you cannot ignore this check.\n \n ### Exceptions\n \n None.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: ShellCheck only supports sh/bash/dash/ksh scripts. Sorry! [SC1071]"},{"from": "gpt", "value": "## ShellCheck only supports sh/bash/dash/ksh scripts. Sorry!\n \n ### Problematic code:\n \n ```sh\n #!/usr/bin/python\n print \"Hello\"\n ```\n \n ### Rationale:\n \n You have specified the shebang of an unsupported language or shell dialect.\n \n ShellCheck only supports a limited number of Bourne-based Unix shells: bash, ksh, dash and POSIX sh.\n \n It does not support scripts written for other shells like Zsh, Csh, Tcsh or PowerShell, and it does not support other scripting languages like PHP, Python, JavaScript or SQL.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Unexpected .. [SC1072]"},{"from": "gpt", "value": "# Unexpected ..\n \n *Note: There is a [known bug](../issues/1036) in the current version when [directives](../wiki/Directive) appear within `then` clauses of `if` blocks that causes Shellcheck to report SC1072 on otherwise valid code. Avoid using directives within `then` clauses - instead place them at the top of the `if` block or another enclosing block. This is fixed on the [online version](https://www.shellcheck.net/) and the next release.*\n \n See [Parser Error](https://github.com/koalaman/shellcheck/wiki/Parser-Error).\n \n This error can also occur with an [incomplete shellcheck directive](https://github.com/koalaman/shellcheck/wiki/Ignore/ceb874a8defc0df77b285e4fc54f897ed9dbb231#ignoring-all-errors-in-a-file-08) like `# shellcheck disable` instead of `# shellcheck disable=all`\n \n ### Problematic code\n ```sh\n # shellcheck disable\n echo stuff that shellcheck up to at least v0.10.0 will not even see because of the incorrect directive above\n ```\n \n ### Correct code\n ```sh\n # shellcheck disable=all\n echo stuff that shellcheck will correctly ignore entirely\n ```\n \n ###\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Couldn't parse this (thing). Fix to allow more checks. [SC1073]"},{"from": "gpt", "value": "# Couldn't parse this (thing). Fix to allow more checks.\n \n This parsing error points to the structure ShellCheck was trying to parse when a parser error occurred. \n \n Make any necessary fixes and check the script again, since most of ShellCheck's functionality can only be applied to scripts that parse successfully.\n \n See [[[Parser error]]](https://www.shellcheck.net/wiki/Parser-error) for more information.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Did you forget the `;;` after the previous case item? [SC1074]"},{"from": "gpt", "value": "## Did you forget the `;;` after the previous case item?\n \n ### Problematic code:\n \n ```bash\n while getoptions f option\n do\n case \"${options}\"\n in\n f) FTR=\"${ARG}\"\n \\?) exit\n esac\n done\n ```\n \n ### Correct code:\n \n ```bash\n while getoptions f option\n do\n case \"${options}\"\n in\n f) FTR=\"${ARG}\";;\n \\?) exit;;\n esac\n done\n ```\n \n ### Rationale:\n Syntax `case` needs `;;` after the previous case item. If not, syntax error will cause.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Use `elif` instead of `else if`. [SC1075]"},{"from": "gpt", "value": "## Use `elif` instead of `else if`.\n \n ### Problematic code:\n \n ```sh\n if [ \"$#\" -eq 0 ]\n then\n echo \"Usage: ...\"\n else if [ \"$#\" -lt 2 ]\n then\n echo \"Missing operand\"\n fi\n \n ```\n \n ### Correct code:\n \n ```sh\n if [ \"$#\" -eq 0 ]\n then\n echo \"Usage: ...\"\n elif [ \"$#\" -lt 2 ]\n then\n echo \"Missing operand\"\n fi\n ```\n ### Rationale:\n \n Many languages allow alternate branches with `else if`, but `sh` is not one of them. Use `elif` instead.\n \n ### Exceptions:\n \n `else if` is a valid (though confusing) way of nesting an `if` statement in a parent's `else`. If this is your intention, consider using canonical formatting by putting a linefeed between `else` and `if`.\n \n This does not change the behavior of the script, but merely makes it more obvious to ShellCheck (and other humans) that you didn't expect the `else if` to behave the way it does in C. Alternatively, you can [[ignore]] it with no ill effects.\n \n ```sh\n \n if x\n then\n echo \"x\"\n else # line break here\n if y\n then\n echo \"y\"\n fi \n fi\n ```\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Trying to do math? Use e.g. `[ $((i/2+7)) -ge 18 ]`. [SC1076]"},{"from": "gpt", "value": "## Trying to do math? Use e.g. `[ $((i/2+7)) -ge 18 ]`.\n \n ### Problematic code:\n \n ```sh\n [ i / 2 + 7 -ge 18 ]\n ```\n \n ### Correct code:\n \n ```sh\n [ $((i / 2 + 7)) -ge 18 ]\n ```\n ### Rationale:\n \n ShellCheck found a loose `+*/%` in a test statement. This usually happens when trying to do arithmetic in a condition, but without using the arithmetic expansion construct `$((expression))`.\n \n In C, `if (a+b == c)` is perfectly fine, but in sh this must be written to first expand the arithmetic operation like `if [ $((a+b)) = c ]`.\n \n ### Exceptions:\n \n None.\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: For command expansion, the tick should slant left (`` ` `` vs `´`). [SC1077]"},{"from": "gpt", "value": "# For command expansion, the tick should slant left (`` ` `` vs `´`).\n \n \n ### Problematic code:\n \n ```sh\n echo \"Your username is ´whoami´\"\n ```\n \n ### Correct code:\n \n ```sh\n echo \"Your username is $(whoami)\" # Preferred\n echo \"Your username is `whoami`\" # Deprecated, will give [SC2006]\n ```\n \n ### Rationale:\n \n In some fonts it's hard to tell ticks apart, but Bash strongly distinguishes between backticks (grave accent `` ` ``), forward ticks (acute accent `´`) and regular ticks (apostrophe `'`).\n \n Backticks start command expansions, while forward ticks are literal. To help spot bugs, ShellCheck parses backticks and forward ticks interchangeably.\n \n ### Exceptions\n \n If you want to write out literal forward ticks, such as fancyful ascii quotation marks:\n \n ```sh\n echo \"``Proprietary software is an injustice.´´ - Richard Stallman\"\n ```\n \n use single quotes instead:\n \n ```sh\n echo '``Proprietary software is an injustice.´´ - Richard Stallman'\n ```\n \n To nest forward ticks in command expansion, use `$(..)` instead of `` `..` ``.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Did you forget to close this double-quoted string? [SC1078]"},{"from": "gpt", "value": "# Did you forget to close this double-quoted string?\n \n ### Problematic code:\n \n ```sh\n greeting=\"hello\n target=\"world\"\n ```\n \n ### Correct code:\n \n ```sh\n greeting=\"hello\"\n target=\"world\"\n ```\n \n ### Rationale:\n \n The first line is missing a quote.\n \n ShellCheck warns when it detects multi-line double quoted, single quoted or backticked strings when the character that follows it looks out of place (and gives a companion warning [[SC1079]] at that spot).\n \n ### Exceptions\n \n If you do want a multiline variable, just make sure the character after it is a quote, space or line feed.\n \n ```sh\n var='multiline\n 'value\n ```\n \n can be rewritten for readability and to remove the warning:\n \n ```sh\n var='multiline\n value'\n ```\n \n As always `` `..` `` should be rewritten to ``$(..)``.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: This is actually an end quote, but due to next char it looks suspect. [SC1079]"},{"from": "gpt", "value": "## This is actually an end quote, but due to next char it looks suspect.\n \n See companion warning [[SC1078]].\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: You need `\\` before line feeds to break lines in `[ ]`. [SC1080]"},{"from": "gpt", "value": "## You need `\\` before line feeds to break lines in `[ ]`.\n \n ### Problematic code:\n \n ```sh\n [ \"$filename\" =\n \"$otherfile\" ]\n ```\n \n ### Correct code:\n \n ```sh\n [ \"$filename\" = \\\n \"$otherfile\" ]\n ```\n ### Rationale:\n \n Bash/ksh `[[ ]]]` can include line breaks anywhere, but `[ ]` requires that you escape them. If you are writing a multi-line `[ .. ]` statement, make sure to include these escapes. If the `[ ]` is supposed to be on a single line, make sure the `]` is there.\n \n ### Exceptions:\n \n None\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Scripts are case-sensitive. Use `if`, not `If`. [SC1081]"},{"from": "gpt", "value": "## Scripts are case-sensitive. Use `if`, not `If`.\n \n ### Problematic code:\n \n ```sh\n If true\n Then\n echo \"hello\"\n Fi\n ```\n \n ### Correct code:\n \n ```sh\n if true\n then\n echo \"hello\"\n fi\n ```\n \n ### Rationale:\n \n Shells are case sensitive and do not accept `If` or `IF` in place of lowercase `if`.\n \n ### Exceptions\n \n If you're aware of this and insist on naming a function `WHILE`, you can quote the name to prevent shellcheck from thinking you meant `while`. Or if you really want the names, add things like `alias If=if IF=if` to replace those keywords and ask shellcheck to ignore them.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: This file has a UTF-8 BOM. Remove it with: `LC_CTYPE=C sed '1s/^...//' < yourscript`. [SC1082]"},{"from": "gpt", "value": "## This file has a UTF-8 BOM. Remove it with: `LC_CTYPE=C sed '1s/^...//' < yourscript`.\n \n ### Problematic code:\n \n This is an encoding error that can't be seen in the script itself, but `cat -v` will show three bytes of garbage at the start of the file:\n \n ```\n $ cat -v file\n M-oM-;M-?#!/bin/bash\n echo \"hello world\"\n ```\n \n ### Correct code:\n \n The code is correct when this garbage does not appear.\n \n ### Rationale:\n \n Some editors may save a file with a [Byte Order Mark](https://en.wikipedia.org/wiki/Byte_order_mark) to mark the file as UTF-8. Shells do not understand this and will give errors on the first line:\n \n ```\n $ bash myscript\n myscript: line 1: #!/bin/sh: No such file or directory\n \n $ dash myscript\n myscript: 1: myscript: #!/bin/sh: not found\n ```\n \n To fix it, remove the byte order mark. One way of doing this is `LC_CTYPE=C sed '1s/^...//' < yourscript`. Verify that it's not there with `cat -v`. \n \n ### Exceptions:\n \n None\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: This `{`/`}` is literal. Check if `;` is missing or quote the expression. [SC1083]"},{"from": "gpt", "value": "## This `{`/`}` is literal. Check if `;` is missing or quote the expression.\n \n ### Problematic code:\n \n ```sh\n rmf() { rm -f \"$@\" }\n ```\n \n or\n \n ```sh\n eval echo \\${foo}\n ```\n \n ### Correct code:\n \n ```sh\n rmf() { rm -f \"$@\"; }\n ```\n \n and\n \n ```sh\n eval \"echo \\${foo}\"\n ```\n \n ### Rationale:\n \n Curly brackets are normally used as syntax in parameter expansion, command grouping and brace expansion.\n \n However, if they don't appear alone at the start of an expression or as part of a parameter or brace expansion, the shell silently treats them as literals. This frequently indicates a bug, so ShellCheck warns about it.\n \n In the example function, the `}` is literal because it's not at the start of an expression. We fix it by adding a `;` before it.\n \n In the example eval, the code works fine. However, we can quiet the warning and follow good practice by adding quotes around the literal data.\n \n ShellCheck does not warn about `{}`, since this is frequently used with `find` and rarely indicates a bug.\n \n ### Exceptions\n \n This error is harmless when the curly brackets are supposed to be literal, in e.g. `awk {'print $1'}`. However, it's cleaner and less error prone to simply include them inside the quotes: `awk '{print $1}'`.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Use `#!`, not `!#`, for the shebang. [SC1084]"},{"from": "gpt", "value": "## Use `#!`, not `!#`, for the shebang.\n \n ### Problematic code:\n \n ```sh\n !#/bin/sh\n echo \"Hello World\"\n ```\n \n ### Correct code:\n \n ```sh\n #!/bin/sh\n echo \"Hello World\"\n ```\n \n ### Rationale:\n \n The shebang has been accidentally swapped. The `#` should come first: `#!`, not `!#`.\n \n ### Exceptions\n \n None.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Don't use `$` on the iterator name in for loops. [SC1086]"},{"from": "gpt", "value": "## Don't use `$` on the iterator name in for loops.\n \n ### Problematic code:\n \n ```sh\n for $var in *\n do\n echo \"$var\"\n done\n ```\n \n ### Correct code:\n \n ```sh\n for var in *\n do\n echo \"$var\"\n done\n ```\n \n ### Rationale:\n \n The variable is named `var`, and can be expanded to its value with `$var`.\n \n The `for` loop expects the variable's name, not its value (and the name can not be specified indirectly).\n \n ### Exceptions\n \n None.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Use braces when expanding arrays, e.g. `${array[idx]}` (or `${var}[..` to quiet). [SC1087]"},{"from": "gpt", "value": "## Use braces when expanding arrays, e.g. `${array[idx]}` (or `${var}[..` to quiet).\n \n ### Problematic code:\n \n ```sh\n echo \"$array[@]\"\n ```\n \n ### Correct code:\n \n ```sh\n echo \"${array[@]}\"\n ```\n \n ### Rationale:\n \n Some languages use the syntax `$array[index]` to access an index of an arrays, but a shell will interpret this as `$array` followed by the unrelated literal string (or glob) `[index]`.\n \n Curly braces are needed to tell the shell that the square brackets are part of the expansion.\n \n ### Exceptions\n \n If you want the square brackets to be treated literally or as a glob, use `${var}[idx]` to prevent this warning.\n \n This does not change how the script works, but clarifies your intent to ShellCheck as well as other programmers.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Parsing stopped here. Invalid use of parentheses? [SC1088]"},{"from": "gpt", "value": "## Parsing stopped here. Invalid use of parentheses?\n \n ### Problematic code:\n \n \n ```sh\n grep ^(.*)\\1$ file\n ```\n \n or\n \n \n ```sh\n var=myfunction(value)\n ```\n \n \n ### Correct code:\n \n ```sh\n grep '^(.*)\\1$' file\n ```\n \n or\n \n ```sh\n var=$(myfunction value)\n ```\n \n ### Rationale:\n \n Parentheses are shell syntax and must be used correctly.\n \n For commands that expect literal parentheses, such as `grep` or `find`, the parentheses need to be quoted or escaped so the shell does not interpret them, but instead passes them to the command.\n \n For shell syntax, the shell does not use them the way most other languages do, so avoid guessing at syntax based on previous experience. In particular:\n \n - Parentheses are NOT used to call functions.\n - Parentheses are NOT used to group expressions, except in arithmetic contexts.\n - Parentheses are NOT used in conditional statements or loops.\n - Parentheses are used differently in different contexts. `( .. )`, `$( .. )`, `$(( .. ))` and `var=(..)` are completely separate and independent structures with different meanings, and can not be broken down into operations on expressions in parentheses.\n \n In C-like languages, `++` can't be broken down into two `+` operations, so you can't e.g. use `+ +` or `+(+)`. In the same way, all of the above are completely unrelated so that you can't do `$(1+1)` or `$( (1+1) )` in place of `$(( 1+1 ))`.\n \n If you are trying to use parentheses for shell syntax, look up the actual syntax of the statement you are trying to use.\n \n ### Exceptions:\n \n None.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Parsing stopped here. Is this keyword correctly matched up? [SC1089]"},{"from": "gpt", "value": "## Parsing stopped here. Is this keyword correctly matched up?\n \n ### Problematic code:\n \n ```sh\n if true\n then\n echo hello\n fi\n fi\n ```\n \n ### Correct code:\n \n ```sh\n if true\n then\n echo hello\n fi\n ```\n \n ### Rationale:\n \n This error is typically seen when there are too many `fi`, `done` or `esac`s, or when there's a `do` or `then` without a corresponding `while`, `for` or `if`. This is often due to deleting a loop or conditional statement but not its terminator.\n \n In some cases, it can even be caused by bad quoting:\n \n ```sh\n var=\"foo\n if [[ $var = \"bar ]\n then\n echo true\n fi\n ```\n \n In this case, the `if` ends up inside the double quotes, leaving the `then` dangling.\n \n ### Exceptions:\n \n None.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Can't follow non-constant source. Use a directive to specify location [SC1090]"},{"from": "gpt", "value": "## Can't follow non-constant source. Use a directive to specify location\n \n ### Problematic code\n \n ```sh\n . \"${util_path}\"\n ```\n \n ### Correct code\n \n ```sh\n # shellcheck source=src/util.sh\n . \"${util_path}\"\n ```\n \n ### Rationale\n \n ShellCheck is not able to include sourced files from paths that are determined at runtime. The file will not be read, potentially resulting in warnings about unassigned variables and similar.\n \n Use a [[Directive]] to point shellcheck to a fixed location it can read instead.\n \n ShellCheck v0.7.2+ will strip a single expansion followed by a slash, e.g. `${var}/util.sh` or `$(dirname \"${BASH_SOURCE[0]}\")/util.sh`, and treat them as `./util.sh`. This allows the use of `source-path` directives or `-P` flags to specify the location.\n \n ### Exceptions\n \n If you don't care that ShellCheck is unable to account for the file, specify `# shellcheck source=/dev/null`.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Not following: (error message here) [SC1091]"},{"from": "gpt", "value": "## Not following: (error message here)\n \n Reasons include: file not found, no permissions, not included on the command line, not allowing `shellcheck` to follow files with `-x`, etc.\n \n ### Problematic code:\n \n ```sh\n source somefile\n ```\n \n ### Correct code:\n \n In case you have access to the file, e.g. if it is included in your source code repository:\n \n ```sh\n # shellcheck source=somefile\n source somefile\n ```\n \n In case you do not have access to the file:\n \n ```sh\n # shellcheck source=/dev/null\n source somefile\n ```\n \n ### Rationale:\n \n ShellCheck, for whichever reason, is not able to access the source file.\n \n This could be because:\n - you did not include it on the command line,\n - did not use `shellcheck -x` (or specified `external-sources=true` in the [[.shellcheckrc|Directive#external-sources]]) to allow following other files\n - don't have permissions, or\n - a variety of other problems.\n \n Feel free to ignore the error with a [[directive]].\n \n ### Exceptions:\n \n ShellCheck is unable to follow dynamic paths, such as `source \"$somedir/file\"`. For these cases, see [SC1090: Can't follow non-constant source. Use a directive to specify location](SC1090) instead. You may be seeing SC1091 because ShellCheck tried to be helpful and strip a leading dynamic path element as described on that page. \n \n If you're fine with it, ignore the message with a [[directive]].\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Stopping at 100 `source` frames :O [SC1092]"},{"from": "gpt", "value": "## Stopping at 100 `source` frames :O\n \n ### Problematic code:\n \n An initial file sourcing a second file, which in turn sources a third file, which in turn sources a fourth file, ...., which in turn sources a 100th file.\n \n ### Correct code:\n \n Anything but that.\n \n ### Rationale:\n \n ShellCheck found a chain of 100+ files sourcing each other. It assumed there must be some internal bug, so it stopped.\n \n ### Exceptions:\n \n If this is intentional, you can cosmetically [[ignore]] this message.\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Parsing of sourced file failed. Ignoring it. [SC1094]"},{"from": "gpt", "value": "## Parsing of sourced file failed. Ignoring it.\n \n ### Problematic code:\n \n ```sh\n source mylib\n ```\n \n ### Correct code:\n \n ```sh\n # shellcheck disable=SC1094\n source mylib\n ```\n \n (or fix `mylib`)\n \n ### Rationale:\n \n ShellCheck encountered a parsing error in a sourced file, `mylib` in the example.\n \n Fix parsing error, or just disable it with a directive.\n \n ### Exceptions:\n \n If the file is fine and this is due to a known `shellcheck` bug, you can ignore it with a [[directive]] as in the example.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: You need a space or linefeed between the function name and body. [SC1095]"},{"from": "gpt", "value": "## You need a space or linefeed between the function name and body.\n \n ### Problematic code:\n \n ```sh\n function foo{\n echo \"hello world\"\n }\n ```\n \n ### Correct code:\n \n Prefer POSIX syntax:\n ```sh\n foo() {\n echo \"hello world\"\n }\n ```\n \n Alternatively, add the missing space between function name and opening `{`:\n ```sh\n # v-- Here\n function foo {\n echo \"hello world\"\n }\n ```\n ### Rationale:\n \n When using `function` keyword function definitions without `()`, a space is required between the function name and the opening `{`.\n \n ### Exceptions:\n \n None.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Unexpected `==`. For assignment, use `=`. For comparison, use `[`/`[[`. [SC1097]"},{"from": "gpt", "value": "## Unexpected `==`. For assignment, use `=`. For comparison, use `[`/`[[`.\n \n ### Problematic code:\n \n ```sh\n var==value\n ```\n \n ### Correct code:\n \n Assignment:\n \n ```sh\n var=value\n ```\n \n Comparison:\n \n ```sh\n [ \"$var\" = value ]\n ```\n \n ### Rationale:\n \n ShellCheck has noticed that you're using `==` in an unexpected way. The two most common reasons for this is:\n \n * You wanted to assign a value but accidentally used `==` instead of `=`.\n \n * You wanted to compare two values, but neglected to use `[ .. ]` or `[[ .. ]]`.\n \n ### Exceptions:\n \n If you wanted to assign a literal equals sign, use quotes to make this clear:\n \n ```sh\n var=\"=sum(A1:A10)\"\n ```\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Quote/escape special characters when using `eval`, e.g. `eval \"a=(b)\"`. [SC1098]"},{"from": "gpt", "value": "## Quote/escape special characters when using `eval`, e.g. `eval \"a=(b)\"`.\n \n ### Problematic code:\n \n ```sh\n eval $var=(a b)\n ```\n \n ### Correct code:\n \n ```sh\n eval \"$var=(a b)\"\n ```\n \n ### Rationale:\n \n Shells differ widely in how they handle unescaped parentheses in `eval` expressions.\n \n * `eval foo=bar` is allowed by dash, bash and ksh.\n * `eval foo=(bar)` is allowed by bash and ksh, but not dash.\n * `eval $var=(bar)` is allowed by ksh, but not bash or dash.\n * `eval foo() ( echo bar; )` is not allowed by any shell.\n \n Since the expression is evaluated as shell script code anyways, it should be passed in as a literal string without relying on special case parsing rules in the target shell. Quote/escape the characters accordingly.\n \n ### Exceptions:\n \n None.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: You need a space before the `#`. [SC1099]"},{"from": "gpt", "value": "## You need a space before the `#`.\n \n ### Problematic code:\n \n ```sh\n while sleep 1\n do# show time\n date\n done\n ```\n \n ### Correct code:\n \n ```sh\n while sleep 1\n do # show time\n date\n done\n ```\n \n ### Rationale:\n \n ShellCheck has noticed that you have a keyword immediately followed by a `#`. In order for the `#` to start a comment, it needs to come after a word boundary such as a space.\n \n ### Exceptions:\n \n None.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: This is a Unicode dash. Delete and retype as ASCII minus. [SC1100]"},{"from": "gpt", "value": "## This is a Unicode dash. Delete and retype as ASCII minus.\n \n ### Problematic code:\n \n ```sh\n [[ 3 –gt 2 ]] # Uses unicode en-dash character\n ```\n \n ### Correct code:\n \n ```sh\n [[ 3 -gt 2 ]] # Uses regular ASCII hyphen-minus character\n ```\n ### Rationale:\n \n A character that looks similar to `-` has made its way into your code. This is usually due to copy-pasting from blogs and other websites that formatted code as text, replacing the ASCII hyphen-minus with a Unicode dash character.\n \n To fix it, simply delete and retype it.\n \n For a large script, you can use your editor's Search&Replace by copy-pasting the bad dash.\n \n ### Exceptions:\n \n None. If you want a literal Unicode dash character, just quote it.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Delete trailing spaces after `\\` to break line (or use quotes for literal space). [SC1101]"},{"from": "gpt", "value": "## Delete trailing spaces after `\\` to break line (or use quotes for literal space).\n \n ### Problematic code:\n \n ```sh\n # There are spaces after the backslash:\n echo hello \\ \n world\n ```\n \n ### Correct code:\n \n ```sh\n # No spaces after the backslash:\n echo hello \\\n world\n ```\n ### Rationale:\n \n To break a line you can use `\\` before the line break. However, if there are spaces after the backslash, the escape will apply to them instead of the line break, and the command will not continue on the next line.\n \n Delete the trailing spaces to make the line break work correctly.\n \n ### Exceptions:\n \n If you do want a literal escaped space at the end of a line you can ignore this error, but please reconsider and use quotes instead. Trailing whitespace is invisible and frequently stripped on purpose (by editor settings / precommits) or accident (copy-paste), and so should not be relied upon for correctness.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Shells disambiguate `$((` differently or not at all. For `$(command substitution)`, add space after `$(` . For `$((arithmetics))`, fix parsing errors. [SC1102]"},{"from": "gpt", "value": "## Shells disambiguate `$((` differently or not at all. For `$(command substitution)`, add space after `$(` . For `$((arithmetics))`, fix parsing errors.\n \n ### Problematic code:\n \n ```sh\n echo \"$((cmd \"$@\") 2>&1)\"\n ```\n \n ### Correct code:\n \n ```sh\n echo \"$( (cmd \"$@\") 2>&1)\"\n ```\n ### Rationale:\n \n You appear to be using `$((` with two (or more) parentheses in a row, where the first `$(` should open a subshell. \n \n This is an ill-defined structure that is parsed differently between different shells and shell versions. Prefer adding spaces to make it unambiguous, both to shells and humans.\n \n Consider the `$(((` in `$(((1)) )`:\n \n Ash, dash and Bash 1 parses it as `$(( (` and subsequently fail to find the matching `))`. Zsh and Bash 2+ looks ahead and parses it as `$( ((`. Ksh parses it as `$( ( (`. \n \n ### Exceptions:\n \n **Alternatively**, you may indeed have correctly spaced your parentheses, but ShellCheck failed to parse `$((` as an arithmetic expression while accidentally succeeding in parsing it as `$(` + `(`. \n \n In these cases, double check the syntax to ensure ShellCheck can parse the `$((`, or ignore this error and hope that it won't affect analysis too severely. \n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: This shell type is unknown. Use e.g. `sh` or `bash`. [SC1103]"},{"from": "gpt", "value": "## This shell type is unknown. Use e.g. `sh` or `bash`.\n \n ### Problematic code:\n \n ```sh\n # shellcheck shell=zsh\n export PAGER=less\n ```\n \n ### Correct code:\n \n Any supported shell on the shebang or the `-s` option\n \n ```sh\n # shellcheck shell=sh\n export PAGER=less\n ```\n \n ### Rationale:\n \n Shellcheck only supports a specific range of shell dialects, there are many more applications providing shell like experiences and some of them look and feel like POSIX shell or bash but does not support the same commands.\n \n One notable unsupported shell type is zsh, see issue [#809](https://github.com/koalaman/shellcheck/issues/809) about supporting zsh - some efforts have been done in the past.\n \n ### Exceptions:\n \n The supported shell types are listed in the help context, at the moment these are\n \n * sh\n * bash\n * dash\n * ksh\n \n ### Related resources:\n \n - Similar rules\n - [[SC1008]] - unrecognized shebang\n - [[SC1071]] - unsupported shebang\n - [[Documentation for shell directive|Directive#shell]]\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Use `#!`, not just `!`, for the shebang. [SC1104]"},{"from": "gpt", "value": "## Use `#!`, not just `!`, for the shebang.\n \n ### Problematic code:\n \n ```sh\n !/bin/sh\n echo \"Hello\"\n ```\n \n ### Correct code:\n \n ```sh\n #!/bin/sh\n echo \"Hello\"\n ```\n \n ### Rationale:\n \n You appear to be specifying an interpreter in a shebang, but it's missing the hash part. The shebang must always start with `#!`. \n \n Even the name \"shebang\" itself comes from \"hash\" (`#`) + \"bang\" (`!`). \n \n ### Exceptions:\n \n None.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Shells disambiguate `((` differently or not at all. If the first `(` should start a subshell, add a space after it. [SC1105]"},{"from": "gpt", "value": "## Shells disambiguate `((` differently or not at all. If the first `(` should start a subshell, add a space after it.\n \n See [[SC1102]], the similar warning for ambiguous `$((`.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: In arithmetic contexts, use `<` instead of `-lt` [SC1106]"},{"from": "gpt", "value": "## In arithmetic contexts, use `<` instead of `-lt`\n \n Similarly, `>` instead of `-gt`, `<=` instead of `-le`, `>=` instead of `-ge`, `==` instead of `-eq`, `!=` instead of `-ne`.\n \n ### Problematic code:\n \n ```sh\n if (( 2 -lt 3 ))\n then\n echo \"True\"\n fi\n ```\n \n ### Correct code:\n \n ```sh\n if (( 2 < 3 ))\n then\n echo \"True\"\n fi\n ```\n \n ### Rationale:\n \n The comparators `-lt`, `-ge`, `-eq` and friends are flags for the `test` command aka `[`. You are instead using it in an arithmetic context, such as `(( .. ))` or `$(( .. ))`, where you should be using `<`, `>=`, `==` etc instead. \n \n In arithmetic contexts, `-lt` is simply interpreted as \"subtract the value of `$lt`\", which is clearly not the intention.\n \n ### Exceptions:\n \n If you do want to subtract `$lt` you can add a space to make this clear to ShellCheck: `echo $((3 - lt))`\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: This directive is unknown. It will be ignored. [SC1107]"},{"from": "gpt", "value": "## This directive is unknown. It will be ignored.\n \n ### Problematic code:\n \n ```sh\n # shellcheck foobar=baz\n echo \"Hello World\"\n ```\n \n ### Correct code:\n \n Depends on your intention.\n \n ### Rationale:\n \n ShellCheck doesn't recognize the [[directive]] you're trying to use in a `# shellcheck` comment. See the [[Directive]]s page for supported directives.\n \n It could be misspelled, or you could be using an older version of shellcheck that doesn't support it yet.\n \n ### Exceptions:\n \n None. If you wish to ignore this warning and continue without it, you need version 0.4.5 (commit 88c56ec) or later and a command grouping:\n \n ```\n # Ignore an unrecognized directive in 0.4.5 or later:\n # shellcheck disable=SC1107\n {\n # shellcheck unrecognized=directive\n echo \"Hello World\"\n }\n ```\n \n Before 0.4.5, unrecognized directives are considered parse errors.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: You need a space before and after the `=` . [SC1108]"},{"from": "gpt", "value": "## You need a space before and after the `=` .\n \n ### Problematic code:\n \n ```sh\n [ \"$var\"= 2 ]\n ```\n \n ### Correct code:\n \n ```sh\n [ \"$var\" = 2 ]\n ```\n ### Rationale:\n \n You appear to be missing the space on the left side of the operator. Shell in general, and `[` in particular, is space sensitive. Operators and operands must be separate tokens. \n \n Please ensure that the operator, like the `=` in the example, has a space both before and after it.\n \n ### Exceptions:\n \n None. If you're comparing values in C style reverse order like `[ -eq == $1 ]`, use quotes: `[ \"-eq\" == \"$1\" ]`. Also, it's pointless since `[ a = b ]` doesn't assign.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: This is an unquoted HTML entity. Replace with corresponding character. [SC1109]"},{"from": "gpt", "value": "## This is an unquoted HTML entity. Replace with corresponding character.\n \n ### Problematic code:\n \n ```sh\n foo && bar\n ```\n \n ### Correct code:\n \n ```sh\n foo && bar\n ```\n \n ### Rationale:\n \n There is an unquoted HTML entity, such as `&`, `>` or `<` (instead of `&`, `>` and `<`) in your code. This usually happens when copy-pasting from a web site that has mismanaged its code formatting.\n \n You should go through the entire script and replace HTML entities with their corresponding characters. \n \n Don't rely on ShellCheck to detect all of them. ShellCheck only warns about certain cases in certain contexts, while this issue tends to affect the entire script.\n \n ### Exceptions:\n \n If you want to run a command called `amp` after backgrounding another command, add a space: `foo & amp;`.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: This is a Unicode quote. Delete and retype it (or quote to make literal). [SC1110]"},{"from": "gpt", "value": "## This is a Unicode quote. Delete and retype it (or quote to make literal).\n \n ### Problematic code:\n \n ```sh\n echo ‘hello world’\n ```\n \n ### Correct code:\n \n ```sh\n echo 'hello world'\n ```\n \n ### Rationale:\n \n Some software, like OS X, Word and WordPress, may automatically replace your regular quotes with slanted Unicode quotes. Try deleting and retyping them, and/or disable “smart quotes” in your editor or OS.\n \n ### Exceptions\n \n If you want to use typographic single quotes, you can put them in double quotes (or typographic double quotes in single quotes) to make shellcheck ignore them, e.g.,\n \n ```sh\n printf \"Warning: ‘wakeonlan’ is not installed.\\n\"\n ```\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: This is a Unicode quote. Delete and retype it (or ignore/singlequote for literal). [SC1111]"},{"from": "gpt", "value": "## This is a Unicode quote. Delete and retype it (or ignore/singlequote for literal).\n \n ### Problematic code:\n \n ```sh\n echo \"hello world”\n ```\n \n ### Correct code:\n \n ```sh\n echo \"hello world\"\n ```\n \n ### Rationale:\n \n Some software, like OS X, Word and WordPress, may automatically replace your regular quotes with slanted Unicode quotes. The shell does not recognize these quotes and will not respect them.\n \n In this case, you have slanted double quotes in a double quoted string. Try deleting and retyping them, and/or disable “smart quotes” in your editor or OS.\n \n ### Exceptions\n \n If you want to use literal slanted double quotes for typographic reasons, you can put them in single quotes to make ShellCheck ignore them:\n \n ```sh\n printf 'Warning: “wakeonlan” is not installed.\\n'\n ```\n \n Alternatively, use single slanted Unicode quotes like so:\n \n ```sh\n printf \"Warning: ‘wakeonlan’ is not installed.\\n\"\n ```\n \n You can also just [[ignore]] this warning.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: This is a Unicode quote. Delete and retype it (or ignore/doublequote for literal). [SC1112]"},{"from": "gpt", "value": "## This is a Unicode quote. Delete and retype it (or ignore/doublequote for literal).\n \n ### Problematic code:\n \n ```sh\n echo 'hello world’\n ```\n \n ### Correct code:\n \n ```sh\n echo 'hello world'\n ```\n \n ### Rationale:\n \n Some software, like OS X, Word and WordPress, may automatically replace your regular quotes with slanted Unicode quotes. The shell does not recognize these quotes and will not respect them.\n \n In this case, you have slanted single quotes in a single quoted string. Try deleting and retyping them, and/or disable “smart quotes” in your editor or OS.\n \n ### Exceptions\n \n If you want to use literal slanted single quotes for typographic reasons, you can put them in double quotes to make ShellCheck ignore them:\n \n ```sh\n printf \"Warning: ‘wakeonlan’ is not installed.\\\\n\"\n ```\n \n You can also just [[ignore]] this warning.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Use `#!`, not just `#`, for the shebang. [SC1113]"},{"from": "gpt", "value": "## Use `#!`, not just `#`, for the shebang.\n \n ### Problematic code:\n \n ```sh\n # /bin/bash\n echo \"Hello World\"\n ```\n \n ### Correct code:\n \n ```sh\n #! /bin/bash\n echo \"Hello World\"\n ```\n ### Rationale:\n \n You appear to be specifying a shebang, but missing the bang (i.e. `!`). The shebang should always be on the form `#!/path/shell`.\n \n ### Exceptions:\n \n None.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Remove leading spaces before the shebang. [SC1114]"},{"from": "gpt", "value": "## Remove leading spaces before the shebang.\n \n ### Problematic code:\n \n ```sh\n #!/bin/sh\n echo \"Hello world\"\n ```\n \n ### Correct code:\n \n ```sh\n #!/bin/sh\n echo \"Hello World\"\n ```\n ### Rationale:\n \n The script has leading spaces before the shebang (`#!`). This is not allowed. \n \n The `#!` should be the first two bytes in the file, as they're used as a file signature by the OS to determine whether a file is a script.\n \n ### Exceptions:\n \n None.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Remove spaces between `#` and `!` in the shebang. [SC1115]"},{"from": "gpt", "value": "## Remove spaces between `#` and `!` in the shebang.\n \n ### Problematic code:\n \n ```sh\n # !/bin/sh\n echo \"Hello World\"\n ```\n \n ### Correct code:\n \n ```sh\n #!/bin/sh\n echo \"Hello World\"\n ```\n ### Rationale:\n \n The script has spaces between the `#` and `!` in the shebang. This is not valid.\n \n Remove the spaces so the OS can correctly recognize the file as a script.\n \n ### Exceptions:\n \n None.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Missing `$` on a `$((..))` expression? (or use `( (` for arrays). [SC1116]"},{"from": "gpt", "value": "## Missing `$` on a `$((..))` expression? (or use `( (` for arrays).\n \n ### Problematic code:\n \n ```sh\n var=((foo+1))\n ```\n \n ### Correct code:\n \n ```sh\n var=$((foo+1))\n ```\n \n ### Rationale:\n \n You appear to be missing the `$` on an assignment from an arithmetic expression `var=$((..))` .\n \n Without the `$`, this is an array expression which is either nested (ksh) or invalid (bash). \n \n ### Exceptions:\n \n If you are trying to define a multidimensional Ksh array, add spaces between the `( (` to clarify:\n \n var=( (1 2 3) (4 5 6) )\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Backslash is literal in `\"\\n\"`. Prefer explicit escaping: `\"\\\\n\"`. [SC1117]"},{"from": "gpt", "value": "## Backslash is literal in `\"\\n\"`. Prefer explicit escaping: `\"\\\\n\"`.\n \n _Note: this warning has been retired due to being too pedantic. Removed in [v0.6.0 - 2018-12-03](https://github.com/koalaman/shellcheck/commit/d8a32da07f36748986e4e34988f5cc50d7f80faa)_\n \n ### Problematic code:\n \n ```sh\n printf \"%s\\n\" \"Hello\"\n ```\n \n ### Correct code:\n \n ```sh\n printf \"%s\\\\n\" \"Hello\"\n ```\n \n or alternatively, with single quotes:\n \n ```sh\n printf '%s\\n' \"Hello\"\n ```\n \n ### Rationale:\n \n In a double quoted string, you have escaped a character that has no special behavior when escaped. Instead, it's invoking the fallback behavior of being interpreted literally.\n \n Instead of relying on this implicit fallback, you should escape the backslash explicitly. This makes it clear that it's meant to be passed as a literal backslash in the string parameter.\n \n ### Exceptions:\n \n None. This is a stylistic issue which can be [[ignored]]. But can you name the 5 characters that *are* special when escaped in double quotes? \n \n They are $, `, \", \\\\, or newline. More infos are available in the [bash manual].\n \n [bash manual]: https://www.gnu.org/software/bash/manual/html_node/Double-Quotes.html\n \n ### Retired:\n \n This warning is no longer emitted as of d8a32da07 (strictly after v0.5).\n \n The number of harmlessly affected `printf`, `sed` and `grep` statements was significantly higher than the number of actual unexpanded escape sequences. It may return some day under a `-pedantic` type flag.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Delete whitespace after the here-doc end token. [SC1118]"},{"from": "gpt", "value": "## Delete whitespace after the here-doc end token.\n \n ### Problematic code:\n \n \"▭\" below indicates an otherwise invisible space:\n \n ```sh\n cat << \"eof\"\n Hello\n eof▭ \n ```\n \n ### Correct code:\n \n ```sh\n cat << \"eof\"\n Hello\n eof\n ```\n ### Rationale:\n \n The end token of your here document has trailing whitespace. This is invisible to the naked eye, but shells do not accept it.\n \n Remove the trailing whitespace.\n \n ### Exceptions:\n \n None.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Add a linefeed between end token and terminating `)`. [SC1119]"},{"from": "gpt", "value": "## Add a linefeed between end token and terminating `)`.\n \n ### Problematic code:\n \n ```sh\n var=$(fmt -s \"$COLUMNS\" << \"eof\"\n This is a bunch of text\n eof)\n \n ```\n \n ### Correct code:\n \n ```sh\n var=$(fmt -s \"$COLUMNS\" << \"eof\"\n This is a bunch of text\n eof\n )\n ```\n ### Rationale:\n \n When embedding a here document in `$(..)` or `(..)`, there needs to be a linefeed (newline) between the here doc token and the closing `)`. Please insert one.\n \n Failing to do so may cause warnings like this:\n \n bash: warning: here-document at line 15 delimited by end-of-file (wanted `eof')`\n dash: 5: Syntax error: end of file unexpected (expecting \")\")\n \n ### Exceptions:\n \n This error may be incorrectly emitted for `ksh`, where this is allowed. In this case, please either write it in a standard way or ignore this warning.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: No comments allowed after here-doc token. Comment the next line instead. [SC1120]"},{"from": "gpt", "value": "## No comments allowed after here-doc token. Comment the next line instead.\n \n ### Problematic code:\n \n ```sh\n cat << eof # --- Start greeting --\n Hello\n eof # --- End greeting ---\n ```\n \n ### Correct code:\n \n ```sh\n cat << eof # --- Start greeting --\n Hello\n eof\n # --- End greeting ---\n ```\n ### Rationale:\n \n The terminator token for a here document must be on an entirely separate line. No comments are allowed on this line.\n \n Place the comment somewhere else, such as on the following line.\n \n ### Exceptions:\n \n None\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Add `;`/`&` terminators (and other syntax) on the line with the `<<`, not here. [SC1121]"},{"from": "gpt", "value": "## Add `;`/`&` terminators (and other syntax) on the line with the `<<`, not here.\n \n ### Problematic code:\n \n ```sh\n sudo bash -s << \"END\"\n cmd1\n cmd2\n END &\n \n ```\n \n ### Correct code:\n \n ```sh\n sudo bash -s << \"END\" &\n cmd1\n cmd2\n END\n ```\n ### Rationale:\n \n You are using `&`, `;`, `&>` or similar after a here document. This is not allowed.\n \n This should instead be part of the line that initiated the here document, i.e. the one with the `<<`. \n \n If it helps, look at `<< \"END\"` as if it was `< file`, and make sure the resulting command is valid. This is what the shell does. You can then append here document data after the command.\n \n ### Exceptions:\n \n None.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Nothing allowed after end token. To continue a command, put it on the line with the `<<`. [SC1122]"},{"from": "gpt", "value": "## Nothing allowed after end token. To continue a command, put it on the line with the `<<`.\n \n ### Problematic code:\n \n ```sh\n cat << EOF\n Hello\n EOF | nl\n ```\n \n ### Correct code:\n \n ```sh\n cat << EOF | nl\n Hello\n EOF\n ```\n ### Rationale:\n \n You have a here document, and appear to have added text after the terminating token.\n \n This is not allowed. If it was meant to continue the command, put it on the line with the `<<`.\n \n If it helps, look at << \"END\" as if it was < file, and make sure the resulting command is valid. This is what the shell does. You can then append here document data after the command.\n \n ### Exceptions:\n \n None\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: ShellCheck directives are only valid in front of complete compound commands, like `if`, not e.g. individual `elif` branches. [SC1123]"},{"from": "gpt", "value": "## ShellCheck directives are only valid in front of complete compound commands, like `if`, not e.g. individual `elif` branches.\n \n ### Problematic code:\n \n ```sh\n if [ \"$prod\" = \"true\" ]\n then\n echo \"Prod mode\"\n # shellcheck disable=2154\n elif [ \"$debug\" = \"true\" ]\n then\n echo \"Debug mode\"\n fi\n ```\n \n ### Correct code:\n ```sh\n # Applies to entire `if...fi` command\n # shellcheck disable=2154\n if [ \"$prod\" = \"true\" ]\n then\n echo \"Prod mode\"\n elif [ \"$debug\" = \"true\" ]\n then\n echo \"Debug mode\"\n fi\n ```\n \n or \n \n ```sh\n if [ \"$prod\" = \"true\" ]\n then\n echo \"Prod mode\"\n elif # Applies only to this [ .. ] command\n # shellcheck disable=2154\n [ \"$debug\" = \"true\" ]\n then\n echo \"Debug mode\"\n fi\n ```\n \n \n ### Rationale:\n \n You appear to have put a directive before a non-command keyword, such as `elif`, `else`, `do`, `;;` or similar. \n \n Unlike many other linters, ShellCheck comment directives apply to the next shell command, rather than to the next line of text.\n \n This means that you can put a directive in front of a `while` loop, `if` statement or function definition, and it will apply to that entire structure.\n \n However, it also means that you can not apply the directive to non-commands like an individual `elif` or `else` block since these are not commands by themselves, and rather just parts of an `if` compound command.\n \n Please move the directive in front of the nearest applicable command that contains the code you want to apply it to, such as before the `if`. \n \n ### Exceptions:\n \n None.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: ShellCheck directives are only valid in front of complete commands like `case` statements, not individual case branches. [SC1124]"},{"from": "gpt", "value": "## ShellCheck directives are only valid in front of complete commands like `case` statements, not individual case branches.\n \n ### Problematic code:\n \n ```sh\n case $? in\n 0) echo \"Success\" ;;\n # shellcheck disable=2154\n *) echo \"$cmd $flag returned failure\" ;;\n esac\n \n ```\n \n ### Correct code:\n ```sh\n # Applies to everything in the `case` statement\n # shellcheck disable=2154\n case $? in\n 0) echo \"Success\" ;;\n *) echo \"$cmd $flag returned failure\" ;;\n esac\n ```\n \n or \n \n ```sh\n case $? in\n 0) echo \"Success\" ;;\n *)\n # Applies to a single command within the `case`\n # shellcheck disable=2154\n echo \"$cmd $flag returned failure\"\n ;;\n esac\n ```\n \n \n ### Rationale:\n \n You appear to have put a directive before a branch in a case statement.\n \n ShellCheck directives can not be scoped to individual branches of `case` statements, only to the entire `case`, or to individual commands within it. Please move the directive as appropriate.\n \n (It is possible to apply directives to all commands within a `{ ..: }` command group, if you truly wish to apply a directive to multiple commands but not the full `case` statement.)\n \n ### Exceptions:\n \n None.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Invalid `key=value` pair in directive [SC1125]"},{"from": "gpt", "value": "## Invalid `key=value` pair in directive\n \n ### Problematic code:\n \n ```sh\n # shellcheck disable=SC2153 (variable not a misspelling)\n ```\n \n ### Correct code:\n \n ```sh\n # shellcheck disable=SC2153 # variable not a misspelling\n ```\n \n ### Rationale:\n \n A comment at the end of a directive must be preceded by a `#`\n to avoid it being interpreted as an instruction.\n The [directive page](Directive#documenting-directive-use)\n contains more guidance about commenting style.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Place shellcheck directives before commands, not after. [SC1126]"},{"from": "gpt", "value": "## Place shellcheck directives before commands, not after.\n \n ### Problematic code:\n \n ```sh\n var=1 # shellcheck disable=SC2034\n ```\n \n ### Correct code:\n \n ```sh\n # shellcheck disable=SC2034\n var=1 \n ```\n ### Rationale:\n \n ShellCheck expects directives to come before the relevant command. They are not allowed after.\n \n ### Exceptions:\n \n If this is not a directive and just a comment mentioning ShellCheck, please rewrite or capitalize:\n \n var=1 # ShellCheck encourages lowercase variable names\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Was this intended as a comment? Use `#` in sh. [SC1127]"},{"from": "gpt", "value": "## Was this intended as a comment? Use `#` in sh.\n \n ### Problematic code:\n \n ```C\n // This is a comment.\n /* This too. */\n ```\n \n ### Correct code:\n \n ```sh\n # This is a comment.\n # This too.\n ```\n ### Rationale:\n \n ShellCheck found what appears to be a C-style comment, a line starting with `//` or `/*`.\n \n In Bourne based shell scripts, the comment character is `#`\n \n ### Exceptions:\n \n None.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: The shebang must be on the first line. Delete blanks and move comments. [SC1128]"},{"from": "gpt", "value": "## The shebang must be on the first line. Delete blanks and move comments.\n \n ### Problematic code:\n \n ```sh\n # Copyright 2018 Foobar, All rights reserved\n #!/bin/bash\n ```\n \n ### Correct code:\n \n ```sh\n #!/bin/bash\n # Copyright 2018 Foobar, All rights reserved\n ```\n \n ### Rationale:\n \n A shebang only has an effect when it appears as the first line in a script. Specifically, the first two bytes of the file must be `#!`.\n \n Adding comments, copyright notices or simply an accidental blank line before it will turn a shebang into an ineffectual comment. This means that the script is no longer in charge of its own interpreter, and may fail to run or produce different results depending on the context it's run (e.g. it may work from `bash` but not from `zsh` or via `sudo`).\n \n Delete any leading blank lines, and move all comments after the shebang.\n \n ### Exceptions:\n \n None\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: You need a space before the `!`. [SC1129]"},{"from": "gpt", "value": "## You need a space before the `!`.\n \n ### Problematic code:\n \n ```sh\n while! [ -f file ]\n do sleep 1; done\n ```\n \n ### Correct code:\n \n ```sh\n while ! [ -f file ]\n do sleep 1; done\n ```\n ### Rationale:\n \n ShellCheck found a keyword immediately followed by a `!`. There needs to be a space between them.\n \n ### Exceptions:\n \n None\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: You need a space before the :. [SC1130]"},{"from": "gpt", "value": "## You need a space before the :.\n \n ### Problematic code:\n \n ```sh\n until make\n do:; done\n ```\n \n ### Correct code:\n \n ```sh\n until make\n do :; done\n ```\n ### Rationale:\n \n ShellCheck found a keyword immediately followed by a `:`. `:` is a synonym for `true`, the command that \"does nothing, successfully\", and as a command name it needs a space. \n \n `do:` is as invalid as `dotrue`. Use `do :`, or preferably, `do true` for readability.\n \n ### Exceptions:\n \n None\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Use `elif` to start another branch. [SC1131]"},{"from": "gpt", "value": "## Use `elif` to start another branch.\n \n ### Problematic code:\n \n ```sh\n if false\n then\n echo \"hi\"\n elseif true\n then\n echo \"ho\"\n fi\n ```\n \n ### Correct code:\n \n ```sh\n if false\n then\n echo \"hi\"\n elif true\n then\n echo \"ho\"\n fi\n ```\n ### Rationale:\n \n ShellCheck noticed that you appear to be using `elseif` or `elsif` as a keyword. This is not valid.\n \n `sh` instead uses `elif` as its alternative branch keyword.\n \n ### Exceptions:\n \n If you have made your own function called `elseif` and intend to call it, you can ignore this message.\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: This `&` terminates the command. Escape it or add space after `&` to silence. [SC1132]"},{"from": "gpt", "value": "## This `&` terminates the command. Escape it or add space after `&` to silence.\n \n ### Problematic code:\n \n ```sh\n curl https://www.google.com/search?q=cats&tbm=isch\n ```\n \n ### Correct code:\n \n ```sh\n curl \"https://www.google.com/search?q=cats&tbm=isch\"\n ```\n ### Rationale:\n \n An unescaped and unquoted `&` terminates the command, but here it's used in the middle of what would otherwise be a shell word. This most commonly happens when copying a URL with query string parameters without escaping the `&`. \n \n Either quote or escape the `&` if you wanted it as a literal ampersand, or add a space after it to make it easier to see where the previous command stopped.\n \n ### Exceptions:\n \n If you do want to background one command and run another, e.g. `sleep 10&wait`, just add a space or linefeed after the `&` to make this more obvious: `sleep 10& wait`\n \n This does not change the meaning of the script, it just makes it clear to ShellCheck (and other humans) that the `&` isn't supposed to be a part of the shell world.\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Unexpected start of line. If breaking lines, `|`/`||`/`&&` should be at the end of the previous one. [SC1133]"},{"from": "gpt", "value": "## Unexpected start of line. If breaking lines, `|`/`||`/`&&` should be at the end of the previous one.\n \n ### Problematic code:\n \n ```sh\n dmesg\n | grep \"error\"\n ```\n \n ### Correct code:\n \n ```sh\n dmesg |\n grep \"error\"\n ```\n \n ### Rationale:\n \n ShellCheck has found a line that unexpectedly started with `|`, `||` or `&&`. This usually happens when a line is broken incorrectly.\n \n When breaking around a `|`, `||` or `&&`, there are two options:\n \n * Break the line *after* this token. `dmesg` is a complete command by itself, but `dmesg |` is not so the shell knows to continue on the next line.\n * Use a `\\` at the end of the previous line to explicitly tell the shell to continue on the next.\n \n ### Exceptions:\n \n In v0.7.2 and below, this warning triggered incorrectly when starting a line with `&>`. In these versions, you can either [[ignore]] the warning, or move the redirection after the command name.\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Error parsing `shellcheckrc`: [SC1134]"},{"from": "gpt", "value": "Error parsing `shellcheckrc`:\n \n ```\n SC1134 (error): Failed to process foo, line bar: Fix any mentioned problems and try again.\n ```\n \n Need more information.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Prefer escape over ending quote to make `$` literal. Instead of `\"It costs $\"5`, use `\"It costs \\$5\"` [SC1135]"},{"from": "gpt", "value": "## Prefer escape over ending quote to make `$` literal. Instead of `\"It costs $\"5`, use `\"It costs \\$5\"`\n \n ### Problematic code:\n \n ```sh\n echo \"The apples are $\"\"1 each\"\n eval \"var=$\"name\n ```\n \n ### Correct code:\n \n ```sh\n echo \"The apples are \\$1 each\"\n eval \"var=\\$name\"\n # or better yet: var=\"${!name}\"\n ```\n \n ### Rationale:\n \n The script appears to be closing a double quoted string for the sole purpose of making a dollar sign `$` literal.\n \n While this happens to work, the better solution is instead to escape it with a backslash. This allows the double quoted string to continue uninterrupted, thereby reducing the visual noise of stopping and starting quotes in the middle of a shell word.\n \n ### Exceptions:\n \n None\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Unexpected characters after terminating `]`. Missing semicolon/linefeed? [SC1136]"},{"from": "gpt", "value": "## Unexpected characters after terminating `]`. Missing semicolon/linefeed?\n _Note: Removed in [V0.7.2 2021-04-20](https://github.com/koalaman/shellcheck/commit/8e332ce87978e6f6afdfabcc15b382983ea32550)_\n \n ### Problematic code:\n \n ```sh\n if [ -e \"foo.txt\" ]: then\n echo \"Exists\"\n fi\n ```\n \n ### Correct code:\n \n ```sh\n if [ -e \"foo.txt\" ]; then\n echo \"Exists\"\n fi\n ```\n ### Rationale:\n \n ShellCheck found unexpected characters after the `]` or `]]` in a `test` expression. In the example, a colon was accidentally used instead of a semicolon.\n \n Similarly, a missing space before a comment (`[ -e foo ]#comment`), an additional square bracket (`[[ -e foo ]]]`), or a missing semicolon before a `then` on the same line (`if [ foo ]then`) can cause this warning.\n \n Make sure the `]` or `]]` is not immediately followed by another shell word character. \n \n \n ### Exceptions:\n \n None\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Missing second `(` to start arithmetic for ((;;)) loop [SC1137]"},{"from": "gpt", "value": "## Missing second `(` to start arithmetic for ((;;)) loop\n \n ### Problematic code:\n \n ```sh\n for (i=0; i<10; i++))\n do\n echo $i\n done\n ```\n \n ### Correct code:\n \n ```sh\n for ((i=0; i<10; i++))\n do\n echo $i\n done\n ```\n ### Rationale:\n \n ShellCheck found an arithmetic `for ((;;))` expression where either the `((` or the `))` did not come as a pair. Make sure to use `(( ))` and not `( )`. \n \n ### Exceptions:\n \n None.\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Remove spaces between (( in arithmetic for loop. [SC1138]"},{"from": "gpt", "value": "## Remove spaces between (( in arithmetic for loop.\n \n ### Problematic code:\n \n ```sh\n for( (i=0; i<10; i++) ); do echo $i; done\n ```\n \n ### Correct code:\n \n ```sh\n for((i=0; i<10; i++)); do echo $i; done\n ```\n ### Rationale:\n \n ShellCheck finds arithmetic for ((;;)) expressions where (( or )) are intervening with spaces\n \n ### Exceptions:\n \n None\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Use `||` instead of `-o` between test commands. [SC1139]"},{"from": "gpt", "value": "## Use `||` instead of `-o` between test commands.\n \n And variations, like \"Use `&&` instead of `and`\".\n \n ### Problematic code:\n \n ```sh\n if [ \"$1\" = \"-v\" ] -o [ -n \"$VERBOSE\" ]\n then\n echo \"Verbose log\"\n fi\n ```\n \n ### Correct code:\n \n ```sh\n if [ \"$1\" = \"-v\" ] || [ -n \"$VERBOSE\" ]\n then\n echo \"Verbose log\"\n fi\n ```\n ### Rationale:\n \n You have a `[ .. ]` or `[[ .. ]]` test expression followed by `-o`/`-a` (or by Python-style `or`/`and`).\n \n `-o` and `-a` work *inside* `[ .. ]`, but they do not work *between* them. The Python operators `or` and `and` are never recognized in Bash.\n \n To join two separate test expressions, instead use `||` for \"logical OR\", or `&&` for \"logical AND\".\n \n ### Exceptions:\n \n None\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Unexpected parameters after condition. Missing `&&`/`||`, or bad expression? [SC1140]"},{"from": "gpt", "value": "## Unexpected parameters after condition. Missing `&&`/`||`, or bad expression?\n \n ### Problematic code:\n \n ```sh\n [ \"$1\" ] input=\"$1\"\n ```\n \n ### Correct code:\n \n ```sh\n [ \"$1\" ] && input=\"$1\"\n ```\n ### Rationale:\n \n ShellCheck found characters (other than redirections) after the `]` or `]]` in a test expression. This is not valid.\n \n This sometimes happens when there was an additional expression or command, but joining `||` or `&&` is missing. Alternatively, it could happen due to typos (like `[[ $1 ]]]` with an extra `]`), or generally from malformed test expressions.\n \n ### Exceptions:\n \n None\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Unexpected tokens after compound command. Bad redirection or missing `;`/`&&`/`||`/`|`? [SC1141]"},{"from": "gpt", "value": "## Unexpected tokens after compound command. Bad redirection or missing `;`/`&&`/`||`/`|`?\n \n ### Problematic code:\n \n ```sh\n while echo \"$2\"; do true; done \\\n head -n \"$1\"\n \n while sleep 1; do date; done > my file\n ```\n \n ### Correct code:\n \n ```sh\n while echo \"$2\"; do true; done \\\n | head -n \"$1\"\n \n while sleep 1; do date; done > \"my file\"\n ```\n ### Rationale:\n \n ShellCheck found unexpected trailing characters after a compound command.\n \n The only things allowed after compound commands are redirections, shell keywords, and the various command separators (`;`, `&`, `|`, `&&`, `||`).\n \n In the first example, a `|` was missing, causing `head` to appear as an unexpected trailing word, instead of being piped to. In the second example, a lack of quoting caused `file` to appear as an unexpected trailing word, instead of being part of the redirection.\n \n Examine your statement and correct the problem.\n \n ### Exceptions:\n \n None\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Use `done < <(cmd)` to redirect from process substitution (currently missing one `<`). [SC1142]"},{"from": "gpt", "value": "## Use `done < <(cmd)` to redirect from process substitution (currently missing one `<`).\n \n ### Problematic code:\n \n ```sh\n sum=0\n while IFS=\"\" read -r n\n do\n (( sum += n ))\n done <(file) \n ```\n \n ### Correct code:\n \n ```sh\n sum=0\n while IFS=\"\" read -r n\n do\n (( sum += n ))\n done < <(file) \n ```\n ### Rationale:\n \n ShellCheck found a `done` keyword followed by a process substitution, e.g. `done <(cmd)`.\n \n The intention was most likely to redirect from this process substitution, in which case you will need one extra `<`: `done < <(cmd)`.\n \n This is because `<(cmd)` expands to a filename (e.g. `/dev/fd/63`), and you need a `<` to redirect from filenames.\n \n ### Exceptions:\n \n None\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: This backslash is part of a comment and does not continue the line. [SC1143]"},{"from": "gpt", "value": "## This backslash is part of a comment and does not continue the line.\n \n ### Problematic code:\n \n ```sh\n sed \\\n -e \"s/HOST/$HOSTNAME/g\" \\\n # -e \"s/USER/$USER/g\" \\\n -e \"s/ARCH/$(uname -m)/g\" \\\n \"$buildfile\"\n ```\n \n ### Correct code:\n \n \n ```sh\n sed \\\n -e \"s/HOST/$HOSTNAME/g\" \\\n -e \"s/ARCH/$(uname -m)/g\" \\\n \"$buildfile\"\n \n # This comment is moved out:\n # -e \"s/USER/$USER/g\" \\\n ```\n \n or using backticked, inlined comments:\n \n ```sh\n sed \\\n -e \"s/HOST/$HOSTNAME/g\" \\\n `# -e \"s/USER/$USER/g\"` \\\n -e \"s/ARCH/$(uname -m)/g\" \\\n \"$buildfile\"\n ```\n \n (ShellCheck recognizes this idiom and does not suggest quotes or `$()`, neither of which would have worked)\n \n ### Rationale:\n \n ShellCheck found a line continuation followed by a commented line that appears to try to do the same.\n \n Backslash line continuations are not respected in comments, and the line instead simply terminates. This is a problem when commenting out one line in a multi-line command like the example.\n \n Instead, either move the line away from its statement, or use an `` `# inline comment` `` in an unquoted backtick command substitution. \n \n ### Exceptions:\n \n None.\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: `external-sources` can only be enabled in .shellcheckrc, not in individual files. [SC1144]"},{"from": "gpt", "value": "## `external-sources` can only be enabled in .shellcheckrc, not in individual files.\n \n ### Problematic code:\n \n ```sh\n # shellcheck external-sources=true\n source /dev/zero\n ```\n \n ### Correct code:\n \n Add `external-sources=true` to `.shellcheckrc`\n \n ### Rationale:\n \n Due to its origins as an online tool, ShellCheck will by default run in a sandbox where it only reads the files explicitly named on the command line.\n \n The `external-sources` [[directive]] allows disabling this, but must be specified in `.shellcheckrc`. This is because the sandbox would be useless if the sandboxed script can disable it for itself.\n \n ### Exceptions:\n \n None.\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Unknown `external-sources` value. Expected `true`/`false`. [SC1145]"},{"from": "gpt", "value": "## Unknown `external-sources` value. Expected `true`/`false`.\n \n ### Problematic code:\n \n `.shellcheckrc`:\n \n ```sh\n external-sources=maybe\n ```\n \n ### Correct code:\n \n ```sh\n external-sources=true\n ```\n \n ### Rationale:\n \n The `external-sources` [[directive]] expects a value of `true` or `false`.\n \n ### Exceptions:\n \n None.\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: See if you can use `${#variable}` instead [SC2000]"},{"from": "gpt", "value": "# See if you can use `${#variable}` instead\n \n `${#variable}` will be equal to the number of characters in `\"${variable}\"`\n \n This is the same result as `\"$( echo \"$variable\" | wc -m )\"`\n When \"$variable\" only contains single-byte characters, it's also the same as `\"$( echo \"$variable\" | wc -c )\"`\n \n ## example code\n \n ``` bash\n #!/usr/bin/env bash\n \n if [ \"$( echo \"$1\" | wc -c )\" -gt 1 ]; then\n echo \"greater than 1\"\n fi\n \n if [ \"$( echo \"$1\" | wc -m )\" -gt 1 ]; then\n echo \"greater than 1\"\n fi\n \n if [ \"${#1}\" -gt 1 ]; then\n echo \"greater than 1\"\n fi\n ```\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: See if you can use `${variable//search/replace}` instead. [SC2001]"},{"from": "gpt", "value": "## See if you can use `${variable//search/replace}` instead.\n \n ### Problematic code:\n \n ```sh\n string=\"stirng\" ; echo \"$string\" | sed -e \"s/ir/ri/\"\n ```\n \n ### Correct code:\n \n ```sh\n string=\"stirng\" ; echo \"${string//ir/ri}\"\n ```\n \n ***\n \n \n Here is a demonstration of the different search/replace available in Bash:\n \n ```bash\n var=\"foo foo\"\n # the following two echo's should be equivalent:\n echo \"$var\" | sed 's/^foo/bar/g'\n echo ${var/#foo/bar}\n ```\n \n | $var | sed expression | bash equivalent | result |\n |-----------|----------------|-----------------|-----------|\n | foo foo | s/foo/bar/ | ${var/foo/bar} | bar foo |\n | foo foo | s/foo/bar/g | ${var//foo/bar} | bar bar |\n | foo foo | s/^foo/bar/ | ${var/#foo/bar} | bar foo |\n | -foo foo | s/^foo/bar/ | ${var/#foo/bar} | -foo foo |\n | -foo foo | s/foo$/bar/ | ${var/%foo/bar} | -foo bar |\n | -foo foo- | s/foo$/bar/ | ${var/%foo/bar} | -foo foo- |\n \n ### Rationale:\n \n Let's assume somewhere earlier in your code, you have put data into a variable (Ex: $string). Now you want to search and replace inside the contents of $string and echo the contents out. You could pass this to sed as done in the example above, but for simple substitutions, a parameter expansion can do it with less overhead.\n \n ### Exceptions\n \n Occasionally a more complex sed substitution is required. For example, getting the last character of a string.\n \n ```sh\n string=\"stirng\" ; echo \"$string\" | sed -e \"s/^.*\\(.\\)$/\\1/\"\n ```\n \n This is a bit simple for the example, and there are alternative ways of doing this in the shell, but this SC2001 flags on several of my crazy complex sed commands beyond this example's scope. Utilizing some of the more complex capabilities of sed is required occasionally, and it is safe to ignore SC2001.\n \n \n ### Related resources:\n \n * Bash Manual: [Shell Parameter Expansion](https://www.gnu.org/software/bash/manual/bashref.html#Shell-Parameter-Expansion)\n * Wooledge BashGuide: [Parameter Expansion](https://mywiki.wooledge.org/BashGuide/Parameters#Parameter_Expansion).\n * Bash Hacker Wiki: [Parameter Expansion](http://wiki.bash-hackers.org/syntax/pe)\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Useless cat. Consider `cmd < file | ..` or `cmd file | ..` instead. [SC2002]"},{"from": "gpt", "value": "# Useless cat. Consider `cmd < file | ..` or `cmd file | ..` instead.\n \n This suggestion was enabled by default up to and including ShellCheck 0.10.0.\n \n In later versions, it is [[optional]]. It must be explicitly enabled with a [[directive]] `enable=useless-use-of-cat` in a `# shellcheck` comment or `.shellcheckrc`\n \n ### Problematic code:\n \n ```sh\n cat file | tr ' ' _ | nl\n cat file | while IFS= read -r i; do echo \"${i%?}\"; done\n ```\n \n ### Correct code:\n \n ```sh\n < file tr ' ' _ | nl \n while IFS= read -r i; do echo \"${i%?}\"; done < file\n ```\n \n ### Rationale:\n \n `cat` is a tool for con\"cat\"enating files. Reading a single file as input to a program is considered a [Useless Use Of Cat (UUOC)](http://en.wikipedia.org/wiki/Cat_(Unix)#Useless_use_of_cat).\n \n It's more efficient and less roundabout to simply use redirection. This is especially true for programs that can benefit from seekable input, like `tail` or `tar`.\n \n Many tools also accept optional filenames, e.g. `grep -q foo file` instead of `cat file | grep -q foo`.\n \n ### Exceptions\n \n Pointing out UUOC is a long standing shell programming tradition, and removing them from a short-lived pipeline in a loop can speed it up by 2x. However, it's not necessarily a good use of time in practice, and rarely affects correctness. [[Ignore]] as you see fit.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: expr is antiquated. Consider rewriting this using `$((..))`, `${}` or `[[ ]]`. [SC2003]"},{"from": "gpt", "value": "# expr is antiquated. Consider rewriting this using `$((..))`, `${}` or `[[ ]]`.\n \n ### Problematic code:\n \n ```sh\n i=$(expr 1 + 2)\n l=$(expr length \"$var\")\n ```\n \n ### Correct code:\n \n ```sh\n i=$((1+2))\n l=${#var}\n ```\n \n **WARNING:** constants with a leading 0 are interpreted as octal numbers by bash, but not by expr. Then you should specify the base when a leading zero may occur:\n ```sh\n $ x=08\n $ echo $(expr 1 + $x)\n 9\n $ echo $((1 + $x))\n -bash: 1 + 08: value too great for base (error token is \"08\")\n $ echo $((1 + 10#$x))\n 9\n ```\n See [issue #1910](https://github.com/koalaman/shellcheck/issues/1910#issuecomment-610439789)\n \n ### Rationale:\n \n [To quote POSIX:](https://pubs.opengroup.org/onlinepubs/009695399/utilities/expr.html#tag_04_50_17)\n \n > The expr utility has a rather difficult syntax [...] In many cases, the arithmetic and string features provided as part of the shell command language are easier to use than their equivalents in expr. Newly written scripts should avoid expr in favor of the new features within the shell.\n \n ### Exceptions\n \n `sh` doesn't have a great replacement for the `:` operator (regex match). ShellCheck tries not to warn when using expr with `:`, but e.g. `op=:; expr string \"$op\" regex` will still trigger it.\n \n Other than that, all uses of `expr` can be rewritten to use modern shell features instead.\n \n Bash has `[[ string =~ regex ]]`, so not even `expr .. : ..` is necessary.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: `$`/`${}` is unnecessary on arithmetic variables. [SC2004]"},{"from": "gpt", "value": "# `$`/`${}` is unnecessary on arithmetic variables.\n \n ### Problematic code:\n \n ```sh\n echo $(($n + ${arr[i]}))\n ```\n \n ### Correct code:\n \n ```sh\n echo $((n + arr[i]))\n ```\n \n ### Rationale:\n \n The `$` or `${..}` on regular variables in arithmetic contexts is unnecessary, and can even lead to subtle bugs. This is because the contents of `$((..))` is first expanded into a string, and then evaluated as an expression:\n \n ```sh\n $ a='1+1'\n $ echo $(($a * 5)) # becomes 1+1*5\n 6\n $ echo $((a * 5)) # evaluates as (1+1)*5\n 10\n ```\n \n The `$` is unavoidable for special variables like `$1` vs `1`, `$#` vs `#`. It's also required when adding modifiers to parameters expansions, like `${#var}` or `${var%-}`. ShellCheck does not warn about these cases.\n \n The `$` is also required (and not warned about) when you need to specify the *base* for a variable value:\n \n ```sh\n $ a=09\n $ echo $((a + 1)) # leading zero forces octal interpretation\n bash: 09: value too great for base (error token is \"09\")\n $ echo $((10#a + 1))\n bash: 10#a: value too great for base (error token is \"10#a\")\n $ echo $((10#$a + 1))\n 10\n ```\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Useless `echo`? Instead of `echo $(cmd)`, just use `cmd` [SC2005]"},{"from": "gpt", "value": "Useless `echo`? Instead of `echo $(cmd)`, just use `cmd`\n --------------------------------------------------------\n \n ### Problematic code:\n \n ```sh\n echo \"$(whoami)\"\n ```\n \n ### Correct code:\n \n ```sh\n whoami\n ```\n \n ### Rationale\n \n ShellCheck found the unnecessary construct `echo \"$(somecommand here)\"`.\n \n This is generally due to a misunderstanding about what `echo` does. It has no role in \"showing on screen\" or similar, but simply writes a string to standard output. This is also how all other programs output data.\n \n `echo \"$(somecommand)\"` will capture the output `somecommand` writes to standard output and write it to standard output, where it was already going. At best this is a no-op, but it may have several other negative effects:\n \n * It disables parallel processing in pipelines, such as `echo \"$(find . -name '*.iso')\" | xargs sha1sum` which does not allow iterating files and checksumming at the same time. Similarly, users don't see incremental updates as programs run.\n * It introduces shell and echo related pitfalls like being unable to output the string `-n`, stripping NUL bytes and trailing linefeeds, and expanding escape sequences in some shells but not others.\n * It suppresses the exit code of the command, so that `echo \"$(grep '^user:' /etc/passwd)\"` no longer returns with failure when the user is not found.\n * It does not allow programs to tailor their output for terminals, such as `ls` vs `echo \"$(ls)\"` where the former outputs columns and colors according to user preferences, while the latter doesn't.\n * It uses unnecessary memory to buffer up the data before writing it where it was already going.\n \n To avoid all this, simply replace `echo \"$(somecommand)\"` with `somecommand` as in the example. It's shorter, faster, and more correct.\n \n ### Exceptions\n \n If you are relying on one of the otherwise detrimental effects for correctness, you can consider one of:\n \n ```\n # Suppress exit code without the other negative effects\n cmd || true\n \n # Disable tty specific output without the other negative effects\n cmd | cat\n \n # Buffer up potentially large output without using more memory or modifying the content in any way\n cmd > file.tmp\n cat file.tmp\n \n # Exactly like `echo \"$(cmd)\"`, but allows output like `-n` and works the same across shells\n printf '%s\\n' \"$(cmd)\"\n ```\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Use `$(...)` notation instead of legacy backticked `` `...` ``. [SC2006]"},{"from": "gpt", "value": "# Use `$(...)` notation instead of legacy backticked `` `...` ``.\n \n ### Problematic code\n \n ```sh\n echo \"You are running on `uname`\"\n ```\n \n ### Correct code\n \n ```sh\n echo \"You are running on $(uname)\"\n ```\n \n ### Rationale\n \n Backtick command substitution `` `...` `` is legacy syntax with several issues.\n \n 1. It has a series of undefined behaviors related to quoting in POSIX.\n 1. It imposes a custom escaping mode with surprising results.\n 1. It's exceptionally hard to nest.\n \n `$(...)` command substitution has none of these problems, and is therefore strongly encouraged.\n \n Note: The `$(...)` syntax was introduced in the 1989 Korn Shell (ksh). Finally, in 2011, Solaris 11 was the last operating system to switch from the Bourne Shell to the Korn Shell. After 2011, all typical shells have supported the POSIX `$(...)` notation.\n \n ### Exceptions\n \n - Some very old, legacy sh implementations, may not support `$(...)` and might require the use of backtick command substitution. See [\\[mc-devel\\] \\[PATCH\\] Prefer $() to backticks in sh script](https://lists.midnight-commander.org/pipermail/mc-devel/2024-November/011241.html) and follow-ups.\n \n ### Related resources:\n \n * [BashFaq: Why is `$(...)` preferred over `` `...` `` (backticks)?](http://mywiki.wooledge.org/BashFAQ/082)\n * [StackOverflow: What is the difference between $(command) and `` `command` `` in shell programming?](https://stackoverflow.com/questions/4708549/shell-programming-whats-the-difference-between-command-and-command)\n * [shfmt](https://github.com/mvdan/sh) will automatically convert the legacy syntax\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Use `$((..))` instead of deprecated `$[..]`. [SC2007]"},{"from": "gpt", "value": "## Use `$((..))` instead of deprecated `$[..]`.\n \n ### Problematic code\n \n ```sh\n n=1\n n=$[n+1]\n ```\n \n ### Correct code\n \n ```sh\n n=1\n n=$((n+1))\n ```\n \n ### Rationale\n \n The `$[..]` syntax was deprecated in Bash 2.0 and replaced with the standard `$((..))` syntax from Korn shell\n \n ### Exceptions\n \n None.\n \n ### See also\n \n - http://unix.stackexchange.com/questions/209833/what-does-a-dollar-sign-followed-by-a-square-bracket-mean-in-bash\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: `echo` doesn't read from stdin, are you sure you should be piping to it? [SC2008]"},{"from": "gpt", "value": "## `echo` doesn't read from stdin, are you sure you should be piping to it?\n _Note: Removed in [v0.4.7 - 2020-03-07](https://github.com/koalaman/shellcheck/commit/5bd33dbf922a04f8b64c2ce3eb40ea6f214aef11)_\n \n ### Problematic code:\n \n ```sh\n find . | echo\n ```\n \n ### Correct code:\n \n ```sh\n find .\n ```\n \n ### Rationale:\n \n You are piping command output to `echo`, but `echo` ignores all piped input.\n \n In particular, `echo` is not responsible for putting output on screen. Commands already output data, and with no further actions that will end up on screen.\n \n ### Exceptions:\n \n None.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Consider using `pgrep` instead of grepping `ps` output. [SC2009]"},{"from": "gpt", "value": "## Consider using `pgrep` instead of grepping `ps` output.\n \n ### Problematic Code:\n \n ```sh\n ps ax | grep -v grep | grep \"$service\" > /dev/null\n ```\n \n ### Correct Code:\n \n ```sh\n pgrep -f \"$service\" > /dev/null\n ```\n \n ### Rationale:\n \n If you are just after a pid from a running program, then pgrep is a much safer alternative. Especially if you are also looking for a pid belonging to a certain user or group. All of the parameters are in one command and it can eliminate multiple greps, cuts, seds, awks, etc.\n \n If you want a field that's not the pid, consider doing this through `ps` + `pgrep` instead of `ps` + `grep`:\n \n ```\n for pid in $(pgrep '^python$')\n do\n user=$(ps -o user= -p \"$pid\")\n echo \"The process $pid is run by $user\"\n done\n ```\n \n This is more robust than `ps .. | grep python | cut ..` because it does not try to match against unrelated fields, such as if the user's name was `pythonguru`.\n \n ### Exceptions\n \n `pgrep` is not POSIX. Please [[ignore]] this warning if you are targeting POSIX userlands.\n \n You can [[ignore]] this error if you are trying to match against something that `pgrep` doesn't support:\n \n ```\n # pgrep does not support filtering by 'nice' value\n # shellcheck disable=SC2009\n ps -axo nice=,pid= | grep -v '^ 0'\n ```\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Don't use `ls | grep`. Use a glob or a for loop with a condition to allow non-alphanumeric filenames. [SC2010]"},{"from": "gpt", "value": "## Don't use `ls | grep`. Use a glob or a for loop with a condition to allow non-alphanumeric filenames.\n \n ### Problematic code:\n \n ```sh\n ls /directory | grep mystring\n ```\n \n or\n \n ```sh\n rm $(ls | grep -v '\\.c$')\n ```\n \n ### Correct code:\n \n ```sh\n # BASH\n shopt -s extglob\n rm -- !(*.c)\n \n # POSIX\n for f in ./*\n do\n case $f in\n *.c) true;;\n *) rm \"$f\";;\n esac\n done\n ```\n \n ### Rationale:\n \n [Parsing ls](https://mywiki.wooledge.org/ParsingLs) is generally a bad idea because the output is fragile and human readable. To better handle non-alphanumeric filenames, use a glob. If you need more advanced matching than a glob can provide, use a `for` loop.\n \n ### Exceptions:\n \n - `ls` has sorting options that are tricky to get right with other commands. If a specific order of files is needed, ls _\\_ | grep might be the best alternative.\n - network shares like AFS behave much faster using ls\n \n ### Related resources:\n \n * [BashFaq: How can I find and safely handle file names containing newlines, spaces or both?](https://mywiki.wooledge.org/BashFAQ/020)\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Use `find -print0` or `find -exec` to better handle non-alphanumeric filenames. [SC2011]"},{"from": "gpt", "value": "## Use `find -print0` or `find -exec` to better handle non-alphanumeric filenames.\n \n ### Problematic code:\n \n ```sh\n ls | xargs -n1 wc -w\n ```\n \n ### Correct code:\n \n ```sh\n find . -maxdepth 1 -print0 | xargs -0 -n1 wc -w\n ```\n \n ```sh\n find . -maxdepth 1 -exec wc -w {} \\;\n ```\n \n ### Rationale:\n \n Using `-print0` separates each output with a NUL character, rather than a newline, which is safer to pipe into `xargs`. Alternatively using `-exec` avoids the problem of piping and parsing filenames in the first place.\n \n See [[SC2012]] for more details on this issue.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Use `find` instead of `ls` to better handle non-alphanumeric filenames. [SC2012]"},{"from": "gpt", "value": "## Use `find` instead of `ls` to better handle non-alphanumeric filenames.\n \n ### Problematic code:\n \n ```sh\n ls -l | grep \" $USER \" | grep '\\.txt$'\n ```\n ```sh\n NUMGZ=\"$(ls -l *.gz | wc -l)\"\n ```\n \n ### Correct code:\n \n ```sh\n find ./*.txt -user \"$USER\" # Using the names of the files\n ```\n ```sh\n gz_files=(*.gz)\n numgz=${#gz_files[@]} # Sometimes, you just need a count\n ````\n ### Rationale:\n \n `ls` is only intended for human consumption: it has a loose, non-standard format and may \"clean up\" filenames to make output easier to read.\n \n Here's an example:\n \n ```sh\n $ ls -l\n total 0\n -rw-r----- 1 me me 0 Feb 5 20:11 foo?bar\n -rw-r----- 1 me me 0 Feb 5 2011 foo?bar\n -rw-r----- 1 me me 0 Feb 5 20:11 foo?bar\n ```\n \n It shows three seemingly identical filenames, and did you spot the time format change? How it formats and what it redacts can differ between locale settings, `ls` version, and whether output is a tty.\n \n ### Tips for replacing `ls` with `find`:\n \n #### Just the filenames, ma'am\n \n (Note that `-maxdepth` is not POSIX, but can be simulated by having the expression call `-prune` on all directories it finds, e.g. `find ./* -prune -print`)\n \n `ls` can usually be replaced by `find` if it's just the filenames, or a count of them, that you're after. Note that if you are using `ls` to get at the contents of a directory, a straight substitution of `find` may not yield the same results as `ls`. Here is an example:\n \n ```\n $ ls -c1 .snapshot\n rnapdev1-svm_4_05am_6every4hours.2019-04-01_1605\n rnapdev1-svm_4_05am_6every4hours.2019-04-01_2005\n rnapdev1-svm_4_05am_6every4hours.2019-04-02_0005\n rnapdev1-svm_4_05am_6every4hours.2019-04-02_0405\n rnapdev1-svm_4_05am_6every4hours.2019-04-02_0805\n rnapdev1-svm_4_05am_6every4hours.2019-04-02_1205\n snapmirror.1501b4aa-3f82-11e8-9c31-00a098cef13d_2147868328.2019-04-01_190000\n ```\n versus\n ```\n $ find .snapshot -maxdepth 1\n .snapshot\n .snapshot/rnapdev1-svm_4_05am_6every4hours.2019-04-02_0005\n .snapshot/rnapdev1-svm_4_05am_6every4hours.2019-04-02_0405\n .snapshot/rnapdev1-svm_4_05am_6every4hours.2019-04-02_0805\n .snapshot/rnapdev1-svm_4_05am_6every4hours.2019-04-01_1605\n .snapshot/rnapdev1-svm_4_05am_6every4hours.2019-04-01_2005\n .snapshot/rnapdev1-svm_4_05am_6every4hours.2019-04-02_1205\n .snapshot/snapmirror.1501b4aa-3f82-11e8-9c31-00a098cef13d_2147868328.2019-04-01_190000\n ```\n You can see two differences here. The first is that the `find` output has the full paths to the found files, relative to the current working directory from which `find` was run whereas `ls` only has the filenames. You may have to adjust your code to not add the directory to the filenames as you process them when moving from `ls` to `find`, or (with GNU find) use `-printf '%P\\n'` to print just the filename.\n \n The second difference in the two outputs is that the `find` command includes the searched directory as an entry. This can be eliminated by also using `-mindepth 1` to skip printing the root path, or using a negative name option for the searched directory:\n ```\n $ find .snapshot -maxdepth 1 ! -name .snapshot\n .snapshot/rnapdev1-svm_4_05am_6every4hours.2019-04-02_0005\n .snapshot/rnapdev1-svm_4_05am_6every4hours.2019-04-02_0405\n .snapshot/rnapdev1-svm_4_05am_6every4hours.2019-04-02_0805\n .snapshot/rnapdev1-svm_4_05am_6every4hours.2019-04-01_1605\n .snapshot/rnapdev1-svm_4_05am_6every4hours.2019-04-01_2005\n .snapshot/rnapdev1-svm_4_05am_6every4hours.2019-04-02_1205\n .snapshot/snapmirror.1501b4aa-3f82-11e8-9c31-00a098cef13d_2147868328.2019-04-01_190000\n ```\n \n **Note:** If the directory argument to `find` is a fully expressed path (`/home/somedir/.snapshot`), then you should use `basename` on the `-name` filter:\n \n ```\n $ theDir=\"$HOME/.snapshot\"\n $ find \"$theDir\" -maxdepth 1 ! -name \"$(basename $theDir)\"\n /home/matt/.snapshot/rnapdev1-svm_4_05am_6every4hours.2019-04-02_0005\n /home/matt/.snapshot/rnapdev1-svm_4_05am_6every4hours.2019-04-02_0405\n /home/matt/.snapshot/rnapdev1-svm_4_05am_6every4hours.2019-04-02_0805\n /home/matt/.snapshot/rnapdev1-svm_4_05am_6every4hours.2019-04-01_1605\n /home/matt/.snapshot/rnapdev1-svm_4_05am_6every4hours.2019-04-01_2005\n /home/matt/.snapshot/rnapdev1-svm_4_05am_6every4hours.2019-04-02_1205\n /home/matt/.snapshot/snapmirror.1501b4aa-3f82-11e8-9c31-00a098cef13d_2147868328.2019-04-01_190000\n ```\n \n #### All the other info\n \n If trying to parse out any other fields, first see whether `stat` (GNU, OS X, FreeBSD) or `find -printf` (GNU) can give you the data you want directly. When trying to determine file size, try: `wc -c`. This is more portable as `wc` is a mandatory unix command, unlike `stat` and `find -printf`. It may be slower as unoptimized `wc -c` may read the entire file rather than just checking its properties. On some systems, `wc -c` adds whitespace to the file size which can be trimmed by double expansion: `$(( $(wc -c < \"filename\") )) `\n \n ### Exceptions:\n \n If the information is intended for the user and not for processing (`ls -l ~/dir | nl; echo \"Ok to delete these files?\"`) you can ignore this error with a [[directive]].\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: To read lines rather than words, pipe/redirect to a `while read` loop. [SC2013]"},{"from": "gpt", "value": "## To read lines rather than words, pipe/redirect to a `while read` loop.\n \n ### Problematic code:\n \n ```sh\n for line in $(cat file | grep -v '^ *#')\n do\n echo \"Line: $line\"\n done\n ```\n \n ### Correct code:\n \n ```sh\n grep -v '^ *#' file | while IFS= read -r line\n do\n echo \"Line: $line\"\n done\n ```\n \n or without a subshell (bash, zsh, ksh):\n \n ```sh\n while IFS= read -r line\n do\n echo \"Line: $line\"\n done < <(grep -v '^ *#' file)\n ```\n \n or without a subshell, with a pipe (more portable, but write a file on the filesystem):\n \n ```sh\n mkfifo mypipe\n grep -v '^ *#' file > mypipe &\n while IFS= read -r line\n do\n echo \"Line: $line\"\n done < mypipe\n rm mypipe\n ```\n \n NOTE: `grep -v '^ *#'` is a placeholder example and not needed. To just loop through a file:\n ```sh\n while IFS= read -r line\n do\n echo \"Line: $line\"\n done < file\n # or: done <<< \"$variable\"\n ```\n \n ### Rationale:\n \n For loops by default (subject to `$IFS`) read word by word. Additionally, glob expansion will occur.\n \n Given this text file:\n \n ```sh\n foo *\n bar\n ```\n \n The for loop will print:\n \n ```sh\n Line: foo\n Line: aardwark.jpg\n Line: bullfrog.jpg\n ...\n ```\n \n The while loop will print:\n \n ```sh\n Line: foo *\n Line: bar\n ```\n \n \n ### Exceptions\n \n If you do want to read word by word, you can set `$IFS` appropriately and disable globbing with `set -f`, and then [[ignore]] this warning. Alternatively, you can pipe through `tr ' ' '\\n'` to turn words into lines, and then use `while read`. In Bash/Ksh, you can also use a `while read -a` loop to get an array of words per line.\n \n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: This will expand once before find runs, not per file found. [SC2014]"},{"from": "gpt", "value": "## This will expand once before find runs, not per file found.\n \n ### Problematic code:\n \n ```sh\n find . -name '*.tar' -exec tar xf {} -C \"$(dirname {})\" \\;\n ```\n \n ### Correct code:\n \n ```sh\n find . -name '*.tar' -exec sh -c 'tar xf \"$1\" -C \"$(dirname \"$1\")\"' _ {} \\;\n ```\n \n ### Rationale:\n \n Bash evaluates any command substitutions before the command they feature in is executed. In this case, the command is `find`. This means that `$(dirname {})` will run **before** `find` runs, and not **while** `find` runs.\n \n To run shell code for each file, we can write a tiny script and inline it with `sh -c`. We add `_` as a dummy argument that becomes `$0`, and a filename argument that becomes `$1` in the inlined script:\n \n ```sh\n $ sh -c 'echo \"$1 is in $(dirname \"$1\")\"' _ \"mydir/myfile\"\n mydir/myfile is in mydir\n ```\n \n This command can be executed by `find -exec`, with `{}` as the filename argument. It executes shell which interprets the inlined script once for each file. Note that the inlined script is single quoted, again to ensure that the expansion does not happen prematurely .\n \n ### Exceptions:\n \n If you don't care (or if you prefer) that it's only expanded once, like when dynamically selecting the executable to be used by all invocations, you can ignore this message.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Note that `A && B || C` is not if-then-else. C may run when A is true. [SC2015]"},{"from": "gpt", "value": "# Note that `A && B || C` is not if-then-else. C may run when A is true.\n \n ### Problematic code:\n \n ```sh\n [[ $dryrun ]] && echo \"Would delete file\" || rm file\n ```\n \n ### Correct code:\n \n ```sh\n if [[ $dryrun ]]\n then\n echo \"Would delete file\"\n else\n rm file\n fi\n ```\n \n ### Rationale:\n \n It's common to use `A && B` to run `B` when `A` is true, and `A || C` to run `C` when `A` is false.\n \n However, combining them into `A && B || C` is not the same as `if A then B else C`.\n \n In this case, if `A` is true but `B` is false, `C` will run.\n \n For the code sample above, if the script was run with stdout closed for any reason (such as explicitly running `script --dryrun >&-`), echo would fail and the file would be deleted, even though `$dryrun` was set!\n \n If an `if` clause is used instead, this problem is avoided.\n \n ### Boring detail:\n \n We can think of the example above as\n ```sh\n ((([[ $dryrun ]]) && echo \"Would delete file\") || rm file)\n ```\n expressing the left-associativity of the `&&` `||` operators.\n \n Whenever a command (strictly, a pipeline) succeeds or fails, the execution proceeds following the next `&&` (for success) or `||` (for failure). (More strictly, the parentheses should be replaced with `{ command; }` to avoid making a subshell, but that's ugly and boring.)\n \n ### Exceptions\n Ignore this warning when you actually do intend to run C when either A or B fails.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Expressions don't expand in single quotes, use double quotes for that. [SC2016]"},{"from": "gpt", "value": "# Expressions don't expand in single quotes, use double quotes for that.\n \n ### Problematic code:\n \n ```sh\n name=World\n echo 'Hello $name' # Outputs Hello $name\n ```\n \n ### Correct code:\n \n ```sh\n name=World\n echo \"Hello $name\" # Outputs Hello World\n ```\n \n ### Rationale:\n \n ShellCheck found an expansion like `$var`, `$(cmd)`, or `` `cmd` `` in single quotes.\n \n Single quotes express all such expansions. If you want the expression to expand, use double quotes instead. \n \n 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:\n \n ```sh\n dialog --msgbox \"Filename $file may not contain any of: \"'`&;\"\\#%$' 10 70\n ```\n \n ### Exceptions\n \n If you know that you want the expression literally without expansion, you can [[ignore]] this message:\n \n ```\n # We want this to output $PATH without expansion\n # shellcheck disable=SC2016\n echo 'PATH=$PATH:/usr/local/bin' >> ~/.bashrc\n ```\n \n ```\n # We also want this variable to expand \"$BASH_SOURCE:$LINE...\" during an execution trace. \n # shellcheck disable=SC2016\n PS4='+$BASH_SOURCE:$LINENO:$FUNCNAME: '\n ```\n \n ```\n # We want to control which environment variables envsubst replaces\n # shellcheck disable=SC2016\n envsubst '${SERVICE_HOST}:${SERVICE_PORT}' config.template > config\n ```\n \n ShellCheck also does not warn about escaped expansions in double quotes:\n \n ```\n echo \"PATH=\\$PATH:/usr/local/bin\" >> ~/.bashrc\n ```\n \n \n This suggestion is primarily meant to help newbies who assume single and double quotes are basically the same, like in Python and JavaScript. It's not at all meant to discourage experienced users from using single quotes in general. If you are well aware of the difference, please do not hesitate to permanently disable this suggestion with `disable=SC2016` in your `.shellcheckrc`. \n \n ShellCheck tries to increase the signal-to-noise ratio of this warning by ignoring certain well known commands that frequently expect literal dollar signs, such as `sh` and `perl`. However, there's a long tail of less common commands and flags that also frequently expect `$`s, and it's not in ShellCheck's scope to try to keep track of them all. When you come across such a command, please [[ignore]] the suggestion, either permanently or for that one instance.\n \n ### Related resources:\n \n * StackOverflow: [How do I use variables in single quoted strings?](https://stackoverflow.com/questions/21192420/how-do-i-use-variables-in-single-quoted-strings)\n * BashFAQ: [Practices](https://mywiki.wooledge.org/BashGuide/Practices)\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Increase precision by replacing `a/b*c` with `a*c/b`. [SC2017]"},{"from": "gpt", "value": "## Increase precision by replacing `a/b*c` with `a*c/b`.\n \n ### Problematic code:\n \n ```sh\n percent=$((count/total*100))\n ```\n \n ### Correct code:\n \n ```sh\n percent=$((count*100/total))\n ```\n \n ### Rationale:\n \n If integer division is performed before multiplication, the intermediate result will be truncated causing a loss of precision.\n \n In this case, if `count=1` and `total=2`, then the problematic code results in `percent=0`, while the correct code gives `percent=50`.\n \n ### Exceptions:\n \n If you want and expect truncation you can ignore this message.\n \n ShellCheck doesn't warn when `b` and `c` are identical expressions, e.g. `a/10*10`, under the assumption that the intent is to rounded to the nearest 10 rather than the no-op of multiply by `1`.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Use `[:lower:]` to support accents and foreign alphabets. [SC2018]"},{"from": "gpt", "value": "## Use `[:lower:]` to support accents and foreign alphabets.\n \n ### Problematic code:\n \n ```sh\n PLATFORM=\"$(uname -s | tr 'A-Z' 'a-z')\"\n ```\n \n ### Correct code:\n \n ```sh\n PLATFORM=\"$(uname -s | tr '[:upper:]' '[:lower:]')\"\n ```\n \n ### Rationale:\n \n `A-Z` and `a-z` are commonly intended to mean \"all uppercase\" and \"all lowercase letters\" respectively. This ignores accented characters in English, and foreign characters in other languages:\n \n $ tr 'a-z' 'A-Z' <<< \"My fiancée ordered a piña colada.\"\n MY FIANCéE ORDERED A PIñA COLADA.\n \n Instead, you can use `[:lower:]` and `[:upper:]` to explicitly specify case:\n \n $ tr '[:lower:]' '[:upper:]' <<< \"My fiancée ordered a piña colada.\"\n MY FIANCÉE ORDERED A PIÑA COLADA.\n \n ### Exceptions:\n \n If you don't want `a-z` to match `é` or `A-Z` to match `Ñ`, you can ignore this message.\n \n As of 2019-09-08, BusyBox `tr` does not support character classes, so you would have to ignore this message.\n \n Note that the examples used here are multibyte characters in UTF-8. Many implementations (including GNU) fails to deal with them. \n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Use `[:upper:]` to support accents and foreign alphabets. [SC2019]"},{"from": "gpt", "value": "## Use `[:upper:]` to support accents and foreign alphabets.\n \n See the equivalent warning for lowercase matching: [[SC2018]]\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: `tr` replaces sets of chars, not words (mentioned due to duplicates). [SC2020]"},{"from": "gpt", "value": "## `tr` replaces sets of chars, not words (mentioned due to duplicates).\n \n ### Problematic code:\n \n ```sh\n echo 'hello world' | tr 'hello' 'goodbye'\n ```\n \n ### Correct code:\n \n ```sh\n echo 'hello world' | sed -e 's/hello/goodbye/g'\n ```\n \n ### Rationale:\n \n `tr` is for `tr`ansliteration, turning some characters into other characters. It doesn't match strings or words, only individual characters.\n \n In this case, it transliterates h->g, e->o, l->d, o->y, resulting in the string \"goddb wbrdd\" instead of \"goodbye world\".\n \n The solution is to use a tool that does string search and replace, such as sed.\n \n ### Exceptions\n \n None.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Don't use `[]` around ranges in `tr`, it replaces literal square brackets. [SC2021]"},{"from": "gpt", "value": "## Don't use `[]` around ranges in `tr`, it replaces literal square brackets.\n \n ### Problematic code:\n \n ```sh\n tr -cd '[a-z]'\n ```\n \n ### Correct code:\n \n ```sh\n tr -cd 'a-z'\n ```\n ### Rationale:\n \n Ancient System V `tr` required brackets around operands, but modern implementations including POSIX, GNU, OS X and *BSD instead treat them as literals.\n \n Unless you want to operate on literal square brackets, don't include them.\n \n ### Exceptions:\n \n If you do want to replace literal square brackets, reorder the expression (e.g. `a-z[]` to make it clear that the brackets are not special).\n \n ShellCheck does not warn about correct usage of `[..]` in character and equivalence classes like `[:lower:]` and `[=e=]`.\n \n ### Note:\n \n Busybox requires `CONFIG_FEATURE_TR_CLASSES` for this to work. If busybox was compiled without this feature, character classes will obviously not be available, and the correct usage is to use `a-z`, not `[a-z]`.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Note that unlike globs, `o*` here matches `ooo` but not `oscar`. [SC2022]"},{"from": "gpt", "value": "## Note that unlike globs, `o*` here matches `ooo` but not `oscar`.\n \n ### Problematic code:\n \n ```sh\n grep 'foo*'\n ```\n \n when wanting to match `food` and `foosball`, but not `mofo` or `keyfob`.\n \n ### Correct code:\n \n ```sh\n grep '^foo'\n ```\n \n ### Rationale:\n \n As a glob, `foo*` means \"Any string starting with foo\", e.g. `food` and `foosball`.\n \n As a regular expression, \"foo*\" means \"f followed by 1 or more o's, anywhere\", e.g. \"mofo\" or \"keyfob\".\n \n This construct is way more common as a glob than as a regex, so ShellCheck notifies you about it.\n \n ### Exceptions\n \n If you're aware of the above, you can ignore this message. If you'd like shellcheck to be quiet, use a [[directive]] or `'fo[o]*'`.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: The shell may override `time` as seen in man time(1). Use `command time ..` for that one. [SC2023]"},{"from": "gpt", "value": "## The shell may override `time` as seen in man time(1). Use `command time ..` for that one.\n \n ### Problematic code:\n \n ```sh\n time -some some\n ```\n \n ### Correct code:\n \n ```sh\n command time -some some\n ```\n \n ### Rationale:\n \n `time` is a built-in command.\n If you would like to use `time` from `$PATH`, you need to use `command` to execute it as a regular command.\n \n ### Exceptions:\n \n None\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: `sudo` doesn't affect redirects. Use `..| sudo tee file` [SC2024]"},{"from": "gpt", "value": "## `sudo` doesn't affect redirects. Use `..| sudo tee file`\n \n or \"Use `..| sudo tee -a file`\" instead of `>>` to append.\n \n or \"Use `sudo cat file | ..`\" instead of `<` to read.\n \n ### Problematic code:\n \n ```\n # Write to a file\n sudo echo 3 > /proc/sys/vm/drop_caches\n \n # Append to a file\n sudo echo 'export FOO=bar' >> /etc/profile\n \n # Read from a file\n sudo wc -l < /etc/shadow\n ```\n \n ### Correct code:\n \n ```\n # Write to a file\n echo 3 | sudo tee /proc/sys/vm/drop_caches > /dev/null\n \n # Append to a file\n echo 'export FOO=bar' | sudo tee -a /etc/profile > /dev/null\n \n # Read from a file\n sudo cat /etc/shadow | wc -l\n ```\n \n ### Rationale:\n \n Redirections are performed by the current shell before `sudo` is started. This means that it will use the current shell's user and permissions to open and read from or write to the file.\n \n * To *read* from a file that requires additional privileges, you can replace `sudo command < file` with `sudo cat file | command`. \n * To *write* to a file that requires additional privileges, you can replace `sudo command > file` with `command | sudo tee file > /dev/null`\n * To *append* to a file, use the above with `tee -a`. \n * If the file does *not* require special privileges but the command *does*, then you are already doing the right thing: please [[ignore]] the message. \n \n The substitutions work by having a command open the file for reading or writing, instead of relying on the current shell. Since the command is run with elevated privileges, it will have access to files that the current user does not.\n \n Note: there is nothing special about `tee`. It's just the simplest command that can both truncate and append to files without help from the shell. Here are equivalent alternatives:\n \n Truncating:\n \n ```\n echo 'data' | sudo dd of=file\n echo 'data' | sudo sed 'w file'\n ```\n \n Appending: \n \n ```\n echo 'data' | sudo awk '{ print $0 >> \"file\" }'\n echo 'data' | sudo sh -c 'cat >> file'\n ```\n \n ### Exceptions\n \n If you want to run a command as root but redirect as the normal user, you can [[ignore]] this message.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Make sure all escape sequences are enclosed in `\\[..\\]` to prevent line wrapping issues. [SC2025]"},{"from": "gpt", "value": "## Make sure all escape sequences are enclosed in `\\[..\\]` to prevent line wrapping issues.\n \n ### Problematic code:\n \n ```sh\n PS1='\\e[36m\\$ \\e(B\\e[m'\n ```\n \n ### Correct code:\n \n ```sh\n PS1='\\[\\e[36m\\]\\$ \\[\\e(B\\e[m\\]'\n ```\n \n ### Rationale:\n \n Bash is unable to determine exactly which parts of your prompt are text and which are terminal codes. You have to help it by wrapping invisible control codes in `\\[..\\]` (and ensuring that visible characters are not wrapped in `\\[..\\]`).\n \n Note: ShellCheck offers this as a helpful hint and not a robust check. Don't rely on ShellCheck to verify that your prompt is correct.\n \n ### Exceptions\n \n None.\n \n ### Related resources:\n \n * [BashFaq: I have a fancy prompt with colors, and now bash doesn't seem to know how wide my terminal is. Lines wrap around incorrectly.](https://mywiki.wooledge.org/BashFAQ/053)\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: This word is outside of quotes. Did you intend to `'nest '\"'single quotes'\"'` instead? [SC2026]"},{"from": "gpt", "value": "## This word is outside of quotes. Did you intend to `'nest '\"'single quotes'\"'` instead?\n \n ### Problematic code:\n \n ```sh\n alias server_uptime='ssh $host 'uptime -p''\n ```\n \n ### Correct code:\n \n ```sh\n alias server_uptime='ssh $host '\"'uptime -p'\"\n ```\n \n ### Rationale:\n \n In the first case, the user has four single quotes on a line, wishfully hoping that the shell will match them up as outer quotes around a string with literal single quotes:\n \n ```sh\n # v--------match--------v\n alias server_uptime='ssh $host 'uptime -p''\n # ^--match--^\n ```\n \n The shell, meanwhile, always terminates single quoted strings at the first possible single quote:\n \n ```sh\n # v---match--v\n alias server_uptime='ssh $host 'uptime -p''\n # ^^\n ```\n \n Which is the same thing as `alias server_uptime='ssh $host uptime' -p`.\n \n There is no way to nest single quotes. However, single quotes can be placed literally in double quotes, so we can instead concatenate a single quoted string and a double quoted string:\n \n ```sh\n # v--match---v\n alias server_uptime='ssh $host '\"'uptime -p'\"\n # ^---match---^\n ```\n \n This results in an alias with embedded single quotes.\n \n ### Exceptions\n \n None.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: The surrounding quotes actually unquote this. Remove or escape them. [SC2027]"},{"from": "gpt", "value": "## The surrounding quotes actually unquote this. Remove or escape them.\n \n ### Problematic code:\n \n ```sh\n echo \"You enter \"$HOSTNAME\". You can smell the wumpus.\" >> /etc/issue\n ```\n \n ### Correct code:\n \n ```sh\n echo \"You enter $HOSTNAME. You can smell the wumpus.\" >> /etc/issue\n ```\n \n ### Rationale:\n \n Always quoting variables and command expansions is good practice, but blindly putting quotes left and right of them is not.\n \n In this case, ShellCheck has noticed that the quotes around the expansion are unquoting it, because the left quote is terminating an existing double quoted string, while the right quote starts a new one:\n \n ```sh\n echo \"You enter \"$HOSTNAME\". You can smell the wumpus.\"\n |----------| |---------------------------|\n Quoted No quotes Quoted\n ```\n \n If the quotes were supposed to be literal, they should be escaped. If the quotes were supposed to quote an expansion (as in the example), they should be removed because this is already a double quoted string.\n \n ### Exceptions\n \n None.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: `echo` won't expand escape sequences. Consider `printf`. [SC2028]"},{"from": "gpt", "value": "## `echo` won't expand escape sequences. Consider `printf`.\n \n ### Problematic code:\n \n ```sh\n echo \"Name:\\t$value\"\n ```\n \n ### Correct code:\n \n ```sh\n printf 'Name:\\t%s\\n' \"$value\"\n ```\n \n ### Rationale:\n \n Backslash escapes like `\\t` and `\\n` are not expanded by echo, and become literal backslash-t, backslash-n.\n \n `printf` does expand these sequences, and should be used instead.\n \n Other, non-portable methods include `echo -e '\\t'` and `echo $'\\t'`. ShellCheck will warn if this is used in a script with shebang `#!/bin/sh`.\n \n If you actually wanted a literal backslash-t, use\n \n ```sh\n echo \"\\\\t\"\n ```\n \n ### Exceptions\n \n None\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Note that, unescaped, this expands on the client side. [SC2029]"},{"from": "gpt", "value": "## Note that, unescaped, this expands on the client side.\n \n ### Problematic code:\n \n ```sh\n ssh host \"echo $HOSTNAME\"\n ```\n \n ### Correct code:\n \n ```sh\n ssh host \"echo \\$HOSTNAME\"\n ```\n \n or\n \n ```sh\n ssh host 'echo $HOSTNAME'\n ```\n \n ### Rationale:\n \n Bash expands all arguments that are not escaped/singlequoted. This means that the problematic code is identical to\n \n ```sh\n ssh host \"echo clienthostname\"\n ```\n \n and will print out the client's hostname, not the server's hostname.\n \n By escaping the `$` in `$HOSTNAME`, it will be transmitted literally and evaluated on the server instead.\n \n ### Exceptions\n \n If you do want your string expanded on the client side, you can safely ignore this message.\n \n Keep in mind that the expanded string will be evaluated again on the server side, so for arbitrary variables and command output, you may need to add a layer of escaping with e.g. `printf %q`.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Modification of var is local (to subshell caused by pipeline). [SC2030]"},{"from": "gpt", "value": "# Modification of var is local (to subshell caused by pipeline).\n \n See companion warning [[SC2031]].\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: var was modified in a subshell. That change might be lost. [SC2031]"},{"from": "gpt", "value": "# var was modified in a subshell. That change might be lost.\n \n ### Problematic code:\n \n There are many ways of accidentally creating subshells, but a common one is piping to a loop:\n \n ```bash\n n=0\n printf \"%s\\n\" {1..10} | while read i; do (( n+=i )); done\n echo $n\n ```\n \n ### Correct code:\n \n ```bash\n # Bash specific: process substitution. Also try shopts like lastpipe.\n n=0\n while read i; do (( n+=i )); done < <(printf \"%s\\n\" {1..10})\n echo $n\n ```\n In `sh`, temporary files, FIFOs or file descriptors can be used instead. When the output of the command can be stored to a variable before entering the loop, here documents are a preferable alternative.\n ```sh\n n=0\n SUMMANDS=\"1\n 2\n 3\n 4\n 5\n 6\n 7\n 8\n 9\n 10\n \"\n while read i; do n=$(( n + i )); done <(subshell2)\n ```\n \n Some forms of grouping:\n \n ```sh\n ( subshell )\n { regular; }\n ```\n \n Backgrounding:\n \n ```sh\n subshell1 &\n subshell2 &\n ```\n \n Anything executed by external processes:\n \n ```sh\n find . -exec subshell1 {} \\;\n find . -print0 | xargs -0 subshell2\n sudo subshell3\n su -c subshell4\n ```\n \n This applies not only to setting variables, but also setting shell options and changing directories.\n \n ### Exceptions\n \n You can ignore this error if you don't care that the changes aren't reflected, because work on the value branches and shouldn't be recombined.\n \n ### Related resources:\n \n * [BashFaq: I set variables in a loop that's in a pipeline. Why do they disappear after the loop terminates?](https://mywiki.wooledge.org/BashFAQ/024)\n * [Bash Pitfalls: grep foo bar | while read -r; do ((count++)); done](https://mywiki.wooledge.org/BashPitfalls#pf8)\n * [StackOverflow: A variable modified inside a while loop is not remembered](https://stackoverflow.com/questions/16854280/a-variable-modified-inside-a-while-loop-is-not-remembered)\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: This function can't be invoked via su on line 42. [SC2032]"},{"from": "gpt", "value": "# This function can't be invoked via su on line 42.\n (or from xargs, sudo, chroot, or other commands)\n \n See companion warning [[SC2033]].\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Shell functions can't be passed to external commands. Use separate script or sh -c. [SC2033]"},{"from": "gpt", "value": "# Shell functions can't be passed to external commands. Use separate script or sh -c.\n \n ### Problematic code:\n \n ```sh\n foo() { bar --baz \"$@\"; frob --baz \"$@\"; };\n find . -exec foo {} +\n ```\n \n ### Correct code:\n \n ```sh\n find . -exec sh -c 'bar --baz \"$@\"; frob --baz \"$@\";' -- {} +\n ```\n \n ### Rationale:\n \n Shell functions are only known to the shell. External commands like `find`, `xargs`, `su` and `sudo` do not recognize shell functions.\n \n Instead, the function contents can be executed in a shell, either through `sh -c` or by creating a separate shell script as an executable file.\n \n ### Exceptions\n \n If you're intentionally passing a word that happens to have the same name as a declared function, you can quote it to make shellcheck ignore it, e.g.\n \n ```sh\n nobody() {\n sudo -u \"nobody\" \"$@\"\n }\n \n ```\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: foo appears unused. Verify it or export it. [SC2034]"},{"from": "gpt", "value": "# foo appears unused. Verify it or export it.\n \n ## Problematic code:\n \n ```sh\n foo=42\n echo \"$FOO\"\n ```\n \n ## Correct code:\n \n ```sh\n foo=42\n echo \"$foo\"\n ```\n \n ## Rationale:\n \n Variables not used for anything are often associated with bugs, so ShellCheck warns about them.\n \n Also note that something like `local let foo=42` does not make a `let` statement local -- it instead declares an additional local variable named `let`.\n \n ## Exceptions\n \n This warning may be falsely emitted when a variable is only referenced indirectly, and for variables that are intentionally unused.\n \n ### Indirection\n \n It's ShellCheck's intended behavior to emit this warning for any variable that is only referenced though indirection:\n \n ```sh\n # foo generates a warning, even though it has five indirect references\n foo=42\n name=foo\n echo \"${!name} $((name))\"\n export \"$name\"; eval \"echo $name\"\n declare -n name; echo \"$name\"\n ```\n \n This is an intentional design decision and not a bug. If you have variables that will not have direct references, consider using an associative array in bash, or just [[Ignore]] the warning. \n \n Tracking indirect references is a common problem for compilers and static analysis tool, and it is known to be unsolvable in the most general case. There are two ways to handle unresolved indirections (which in a realistic program will essentially be all of them):\n \n * Avoid false positives by assuming all variables may potentially be used (disable all unused variable warnings)\n * Keep true positives by allowing some false positives (emit unused variable warnings that may be incorrect)\n \n Compilers are forced to do the former, but static analysis tools generally do the latter. This includes `pylint`, `jshint` and `shellcheck` itself. This is a design decision meant to make the tools more helpful at the expense of some noise. For consistency and to avoid giving the impression that it should work more generally, ShellCheck does not attempt to resolve even trivial indirections.\n \n #### Intentionally unused variables\n \n For throwaway variables, consider using `_` as a dummy:\n \n ```sh\n read _ last _ zip _ _ <<< \"$str\"\n echo \"$last, $zip\"\n ```\n \n Or optionally as a prefix for dummy variables (ShellCheck >0.7.2).\n \n ```sh ​\n read _first last _email zip _lat _lng <<< \"$str\"\n echo \"$last, $zip\"\n ```\n \n For versions <= 0.7.2, the message can optionally be [[ignore]]d with a directive:\n \n ```sh\n # shellcheck disable=SC2034 # Unused variables left for readability\n read first last email zip lat lng <<< \"$str\"\n echo \"$last, $zip\"\n ```\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Use `./*glob*` or `-- *glob*` so names with dashes won't become options. [SC2035]"},{"from": "gpt", "value": "## Use `./*glob*` or `-- *glob*` so names with dashes won't become options.\n \n ### Problematic code:\n rm *\n \n ### Correct code:\n \n rm ./*\n \n or\n \n rm -- *\n \n ### Rationale\n \n Since files and arguments are strings passed the same way, programs can't properly determine which is which, and rely on dashes to determine what's what.\n \n A file named `-f` (`touch -- -f`) will not be deleted by the problematic code. It will instead be interpreted as a command line option, and `rm` will even report success.\n \n Using `./*` will instead cause the glob to be expanded into `./-f`, which no program will treat as an option.\n \n Similarly, `--` by convention indicates the end of options, and nothing after it will be treated like flags (except for some programs possibly still special casing `-` as e.g. stdin).\n \n Note that changing `*` to `./*` in GNU Tar parameters will add `./` prefix to path names in the created archive. This may cause subtle problems (eg. to search for a specific file in archive, the `./` prefix must be specified as well). So using `-- *` is a safer fix for GNU Tar commands.\n \n `echo` and `printf` do not have issues unless the glob is the first word in the command. ShellCheck 0.7.2+ does not warn for these commands. \n \n For more information, see \"[Filenames and Pathnames in Shell: How to do it Correctly](https://dwheeler.com/essays/filenames-in-shell.html)\".\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: If you wanted to assign the output of the pipeline, use `a=$(b | c)` . [SC2036]"},{"from": "gpt", "value": "## If you wanted to assign the output of the pipeline, use `a=$(b | c)` .\n \n ### Problematic code:\n \n ```sh\n sum=find | wc -l\n ```\n \n ### Correct code:\n \n ```sh\n sum=$(find | wc -l)\n ```\n \n ### Rationale:\n \n The intention in this code was that `sum` would in some way get the value of the command `find | wc -l`.\n \n However, `|` has precedence over the `=`, so the command is a two stage pipeline consisting of `sum=find` and `wc -l`.\n \n `sum=find` is a plain string assignment. Since it happens by itself in an independent pipeline stage, it has no effect: it produces no output, and the variable disappears when the pipeline stage finishes. Because the assignment produces no output, `wc -l` will count 0 lines.\n \n To instead actually assign a variable with the output of a command, command substitution `$(..)` can be used.\n \n ### Exceptions:\n \n None. This warning is triggered whenever the first stage of a pipeline is a single assignment, which is never correct.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: To assign the output of a command, use `var=$(cmd)` . [SC2037]"},{"from": "gpt", "value": "## To assign the output of a command, use `var=$(cmd)` .\n \n ### Problematic code:\n \n ```sh\n var=grep -c pattern file\n ```\n \n ### Correct code:\n \n ```sh\n var=$(grep -c pattern file)\n ```\n ### Rationale:\n \n To assign the output of a command to a variable, use `$(command substitution)`. Just typing a command after the `=` sign does not work.\n \n ### Exceptions:\n \n None. \n \n This warning triggers generally for `var=value -flag` and `var=value *glob*`. See related warning [[SC2209]] which matches `var=commonCommand`. \n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Use `-print0`/`-0` or `find -exec +` to allow for non-alphanumeric filenames. [SC2038]"},{"from": "gpt", "value": "## Use `-print0`/`-0` or `find -exec +` to allow for non-alphanumeric filenames.\n \n ### Problematic code:\n \n ```sh\n find . -type f | xargs md5sum\n ```\n \n ### Correct code:\n \n ```sh\n find . -type f -print0 | xargs -0 md5sum\n find . -type f -exec md5sum {} +\n ```\n \n ### Rationale:\n \n By default, `xargs` interprets spaces and quotes in an unsafe and unexpected way. Whenever it's used, it should be used with `-0` or `--null` to split on `\\0` bytes, and `find` should be made to output `\\0` separated filenames.\n \n POSIX does not require find or xargs to support null terminators, so you can also use `find -exec +`. \n ### Exceptions\n \n None.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: In POSIX sh, *something* is undefined. [SC2039]"},{"from": "gpt", "value": "## In POSIX sh, *something* is undefined.\n \n *Note: This warning has been retired in favor of individual SC3xxx warnings for each individual issue. Removed in [V0.7.2 - 2021-04-19](https://github.com/koalaman/shellcheck/commit/cfd68ee0c2ebfd0ab08a1d4bf628162b454dc207)*\n \n You have declared that your script works with `/bin/sh`, but you are using features that have undefined behavior according to the POSIX specification. \n \n It may currently work for you, but it can or will fail on other OS, the same OS with different configurations, from different contexts (like initramfs/chroot), or in different versions of the same OS, including future updates to your current system.\n \n Either declare that your script requires a specific shell like `#!/bin/bash` or `#!/bin/dash`, or rewrite the script in a portable way.\n \n For help with rewrites, the Ubuntu wiki has [a list of portability issues](https://wiki.ubuntu.com/DashAsBinSh) that broke people's `#!/bin/sh` scripts when Ubuntu switched from Bash to Dash. See also [Bashism](http://mywiki.wooledge.org/Bashism) on wooledge's wiki. ShellCheck may not warn about all these issues.\n \n ### `$'c-style-escapes'`\n \n bash, ksh:\n \n ```Bash\n a=$' \\t\\n'\n ```\n \n POSIX:\n \n ```sh\n a=\"$(printf '%b_' ' \\t\\n')\"; a=\"${a%_}\" # protect trailing \\n\n ```\n \n Want some good news? See http://austingroupbugs.net/view.php?id=249#c590.\n \n ### Testing Equality\n \n `==` operator is not supported in POSIX `sh`\n \n Bash:\n \n ```Bash\n if [ \"$a\" == \"$b\" ]; then\n echo \"equal\"\n fi\n ```\n \n POSIX:\n \n ```sh\n if [ \"$a\" = \"$b\" ]; then\n echo \"equal\"\n fi\n ```\n \n ### `$\"msgid\"`\n \n Bash:\n \n ```Bash\n echo $\"foo $(bar) baz\"\n ```\n \n POSIX:\n \n ```sh\n . gettext.sh # GNU Gettext sh library\n # ...\n barout=$(bar)\n eval_gettext 'foo $barout baz' # See GNU Gettext doc for more info.\n ```\n \n Or you can change them to normal double quotes so you go without `gettext`.\n \n ### `${var:1}` (substring expansion)\n \n https://wiki.ubuntu.com/DashAsBinSh#A.24.7Bfoo:3.5B:1.5D.7D\n \n ### Arithmetic `for` loops\n \n Bash:\n \n ```Bash\n for ((init; test; next)); do foo; done\n ```\n \n POSIX:\n \n ```sh\n : $((init))\n while [ $((test)) -ne 0 ]; do foo; : $((next)); done\n ```\n \n ### Arithmetic exponentiation\n \n Bash:\n \n ```Bash\n printf \"%s\\n\" \"$(( 2**63 ))\"\n ```\n \n POSIX:\n \n The POSIX standard does not allow for exponents. However, you can replicate them completely built-in using a POSIX compatible function. As an example, the `pow` function from [here](http://unix.stackexchange.com/a/7925).\n \n ```sh\n pow() {\n set -- \"$1\" \"$2\" 1\n while [ \"$2\" -gt 0 ]; do\n set -- \"$1\" $(($2-1)) $(($1*$3))\n done\n # %d = signed decimal, %u = unsigned decimal\n # Either should overflow to 0\n printf \"%d\\n\" \"$3\"\n }\n ```\n \n To compare:\n \n ```sh\n $ echo \"$(( 2**62 ))\"\n 4611686018427387904\n $ pow 2 62\n 4611686018427387904\n ```\n \n Alternatively, if you don't mind using an external program, you can use `bc`. Be aware though: `bash` and other programs may abide by a certain maximum integer that `bc` does not (for `bash` that's: 64-bit signed long int, failing back to 32-bit signed long int). \n \n Example:\n \n ```Bash\n # Note the overflow that gives a negative number\n $ echo \"$(( 2**63 ))\"\n -9223372036854775808\n \n # No such problem\n $ echo 2^63 | bc\n 9223372036854775808\n \n # 'bc' just keeps on going\n $ echo 2^1280 | bc\n 20815864389328798163850480654728171077230524494533409610638224700807\\\n 21611934672059602447888346464836968484322790856201558276713249664692\\\n 98162798132113546415258482590187784406915463666993231671009459188410\\\n 95379622423387354295096957733925002768876520583464697770622321657076\\\n 83317005651120933244966378183760369413644440628104205339687097746591\\\n 6057756101739472373801429441421111406337458176\n ```\n \n ### standalone `((..))`\n \n Bash:\n \n ```Bash\n ((a=c+d))\n ((d)) && echo d is true.\n ```\n \n POSIX:\n \n ```sh\n : $((a=c+d)) # discard the output of the arith expn with `:` command\n [ $((d)) -ne 0 ] && echo d is true. # manually check non-zero => true\n ```\n \n ### `select` loops\n \n It takes extra care over terminal columns to make select loop look like bash's, which generates a list with multiple items on one line, or like `ls`.\n \n It is, however, still possible to make a naive translation for `select foo in bar baz; do eat; done`:\n \n ```sh\n while\n _i=0 _foo= foo=\n for _name in bar baz; do echo \"$((_i+=1))) $_name\"; done\n printf '$# '; read _foo\n do\n case _foo in 1) foo=bar;; 2) foo=baz;; *) continue;; esac\n eat\n done\n ```\n \n ### Here-strings\n \n Bash, ksh:\n \n ```Bash\n read aaa bbb <<< $(grep foo bar)\n ```\n \n POSIX:\n \n ```sh\n read aaa bbb << EOF\n $(grep foo bar)\n EOF\n ```\n \n ### echo flags\n \n See https://unix.stackexchange.com/tags/echo/info.\n \n ### `${var/pat/replacement}`\n \n Bash:\n \n ```Bash\n echo \"${TERM/%-256*}\"\n ```\n \n POSIX:\n \n ```sh\n echo \"$TERM\" | sed -e 's/-256.*$//g'\n # Special case for this since we are matching the end (the start [#] also works):\n echo \"${TERM%-256*}\"\n ```\n \n ### `printf %q`\n \n Bash:\n \n ```Bash\n printf '%q ' \"$@\"\n ```\n \n POSIX:\n \n ```sh\n # TODO: Interpret it back to printf escapes for hard-to-copy chars like \\t?\n # See also: http://git.savannah.gnu.org/cgit/libtool.git/tree/gl/build-aux/funclib.sh?id=c60e054#n1029\n reuse_quote()(\n for i; do\n __i_quote=$(printf '%s\\n' \"$i\" | sed -e \"s/'/'\\\\\\\\''/g\"; echo x)\n printf \"'%s'\" \"${__i_quote%x}\"\n done\n )\n reuse_quote \"$@\"\n ```\n \n ### `jobs` flags\n \n The only acceptable flags under POSIX sh for `jobs` are `-l` and `-p` ([see spec](https://pubs.opengroup.org/onlinepubs/9699919799/utilities/jobs.html)). Common flags supported by other shells are `-s` and `-r`, to check for stopped/suspended jobs and running jobs. A portable alternative is using `grep` or `awk`:\n ```sh\n \"$(jobs | awk '/(S|s)(topped|uspended)/')\" # instead of jobs -s\n \"$(jobs | awk '/(R|r)(unning)/')\" # instead of jobs -r\n ```\n Although the state of stopped jobs is `Stopped` in Bash and dash, and it's the one specified by POSIX, `Suspended` is also a valid alternative (but Zsh happens to not respect the capitalization, that's why we try to match `suspended`). Similarly, the state of running jobs is `Running` according to POSIX. Bash and dash respect this, but Zsh uses `running`.\n \n ### Redirect both stdout and stderr\n \n Change:\n ```\n >& and &>\n ```\n \n To:\n ```\n command > file 2>&1 or command 2>&1 | othercommand\n ```\n \n No Comments / Exceptions\n \n ### Prefixing signal names with `SIG`\n \n Instead of e.g.:\n ```sh\n trap my_handler SIGTERM\n ```\n \n use:\n ```sh\n trap my_handler TERM\n # or (`trap -l` for a list of signal numbers; not every one is portable!)\n trap my_handler 15\n ```\n \n ### disown\n \n Bash:\n \n ```Bash\n \n disown %\n ```\n \n POSIX:\n \n ```sh\n nohup \n ```\n \n Note that while `nohup` can be used to achieve the same result, their semantics is different.\n Also note that `nohup` will, by default, redirect input and output.\n \n ## Errors with changed codes\n \n Some errors, currently having their own pages, were linked to this page in older ShellCheck versions.\n \n - [SC3026: In POSIX sh, `^` in place of `!` in glob bracket expressions is undefined.](SC3026)\n \n ## Exception\n \n Depends on what your expected POSIX shell providers would use.\n \n Some features have POSIX proposals:\n * `local`: https://www.austingroupbugs.net/bug_view_page.php?bug_id=767\n * `$'c-style-escape'`: see above\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: `#!/bin/sh` was specified, so ____ is not supported, even when sh is actually bash. [SC2040]"},{"from": "gpt", "value": "## `#!/bin/sh` was specified, so ____ is not supported, even when sh is actually bash.\n \n _Note: Removed in [v0.4.2 - 2016-01-10](https://github.com/koalaman/shellcheck/commit/f77821625c8e9203712f276d470341459ee60455)_\n \n The shebang indicates that the script works with `/bin/sh`, but you are using non-standard features that may not work with `/bin/sh`, **even if /bin/sh is actually bash**. Bash behaves differently when invoked as `sh`, and disabling support for the highlighted feature is one part of that.\n \n Specify `#!/usr/bin/env bash` to ensure that bash (or your shell of choice) will be used, or rewrite the script to be more portable.\n \n The Ubuntu wiki has [a list of portability issues](https://wiki.ubuntu.com/DashAsBinSh) and suggestions on how to rewrite them.\n \n \n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: This is a literal string. To run as a command, use `$(..)` instead of `'..'` . [SC2041]"},{"from": "gpt", "value": "## This is a literal string. To run as a command, use `$(..)` instead of `'..'` .\n \n ### Problematic code:\n \n ```sh\n for i in 'seq 1 10'\n do\n echo \"$i\"\n done\n ```\n \n ### Correct code:\n \n ```sh\n for i in $(seq 1 10)\n do\n echo \"$i\"\n done\n ```\n \n ### Rationale:\n \n The intent was to run the code in the single quotes. This would have worked with slanted backticks, `` `..` ``, but here the very similar looking single quotes `'..'` were used, resulting in a string literal instead of command output.\n \n This is one of the many problems with backticks, so it's better to use `$(..)` to expand commands.\n \n ### Exceptions:\n \n None.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Use spaces, not commas, to separate loop elements. [SC2042]"},{"from": "gpt", "value": "## Use spaces, not commas, to separate loop elements.\n \n ### Problematic code:\n \n ```sh\n for f in foo,bar,baz\n do\n echo \"$f\"\n done\n ```\n \n ### Correct code:\n \n ```sh\n for f in foo bar baz\n do\n echo \"$f\"\n done\n ```\n ### Rationale:\n \n ShellCheck found a `for` loop where the items appeared to be delimited by commas. These will be treated as literal commas. Use spaces instead.\n \n ### Exceptions:\n \n None\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: This loop will only ever run once for a constant value. Did you perhaps mean to loop over `dir/*`, `$var` or `$(cmd)`? [SC2043]"},{"from": "gpt", "value": "## This loop will only ever run once for a constant value. Did you perhaps mean to loop over `dir/*`, `$var` or `$(cmd)`?\n \n ### Problematic code:\n \n ```sh\n for var in value\n do\n echo \"$var\"\n done\n ```\n \n ### Correct code:\n \n Correct code depends on what you want to do.\n \n To iterate over files in a directory, instead of `for var in /my/dir` use:\n \n ```sh\n for var in /my/dir/* ; do echo \"$var\"; done\n ```\n \n To iterate over lines in a file or command output, use a while read loop instead:\n \n ```sh\n mycommand | while IFS= read -r line; do echo \"$line\"; done\n ```\n \n To iterate over *words* written to a command or function's stdout, instead of `for var in myfunction`, use\n \n ```sh\n for var in $(myfunction); do echo \"$var\"; done\n ```\n \n To iterate over *words* in a variable, instead of `for var in myvariable`, use\n \n ```sh\n for var in $myvariable; do echo \"$var\"; done\n ```\n \n \n \n ### Rationale:\n \n ShellCheck has detected that your for loop iterates over a single, constant value. This is most likely a bug in your code, caused by you not expanding the value in the way you want.\n \n You should make sure that whatever you loop over will expand into multiple words.\n \n ### Exceptions\n \n If you stylistically choose to use `for` loops with a single element, e.g. to align with other code or to set up for future extensibility (`for target in x86_64; do ..`), you can [[ignore]] this warning.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: For loops over find output are fragile. Use `find -exec` or a `while read` loop. [SC2044]"},{"from": "gpt", "value": "## For loops over find output are fragile. Use `find -exec` or a `while read` loop.\n \n ### Problematic code:\n \n ```sh\n for file in $(find mydir -mtime -7 -name '*.mp3')\n do\n (( count++ ))\n echo \"Playing file no. $count\"\n play \"$file\"\n done\n echo \"Played $count files\"\n ```\n \n This will fail for filenames containing spaces and similar, such as `My File.mp3`, and has a series of potential globbing issues depending on other filenames in the directory like (if you have `MyFile2.mp3` and `MyFile[2014].mp3`, the former file will play twice and the latter will not play at all).\n \n ### Correct code:\n \n There are many possible fixes, each with its pros and cons.\n \n The most general fix (that requires the least amount of thinking to apply) is having `find` output a `\\0` separated list of files and consuming them in a `while read` loop:\n \n ```sh\n while IFS= read -r -d '' file\n do\n (( count++ ))\n echo \"Playing file no. $count\"\n play \"$file\"\n done < <(find mydir -mtime -7 -name '*.mp3' -print0)\n echo \"Played $count files\"\n ```\n \n In usage it's very similar to the `for` loop: it gets its output from a `find` statement, it executes a shell script body, it allows updating/aggregating variables, and the variables are available when the loop ends.\n \n It requires Bash, and works with GNU, Busybox, OS X, FreeBSD and OpenBSD find, but not POSIX find.\n \n ##### If `find` is just matching globs recursively\n \n If you don't need `find` logic like `-mtime -7` and just use it to match globs recursively (all `*.mp3` files under a directory), you can instead use `globstar` and `nullglob` instead of `find`, and still use a `for` loop:\n \n ```sh\n shopt -s globstar nullglob\n for file in mydir/**/*.mp3\n do\n (( count++ ))\n echo \"Playing file no. $count\"\n play \"$file\"\n done\n echo \"Played $count files\"\n ```\n \n This is bash 4 specific.\n \n \n ##### For POSIX\n \n If you need POSIX compliance, this is a fair approach:\n \n ```sh\n find mydir ! -name \"$(printf \"*\\n*\")\" -name '*.mp3' > tmp\n while IFS= read -r file\n do\n let count++\n echo \"Playing file #$count\"\n play \"$file\"\n done < tmp\n rm tmp\n echo \"Played $count files\"\n ```\n \n The only problem is for filenames containing line feeds. A `! -name \"$(printf \"*\\n*\")\"` has been added to simply skip these files, just in case there are any.\n \n If you don't need variables to be available after the loop (here, if you don't need to print the final play count at the end), you can skip the `tmp` file and just pipe from `find` to `while`.\n \n ##### For simple commands with no aggregation\n \n If you don't need a shell script loop body or any form of variable like if we only wanted to play the file, we can dramatically simplify while maintaining POSIX compatibility:\n \n ```sh\n # Simple and POSIX\n find mydir -name '*.mp3' -exec play {} \\;\n ```\n \n This does not allow things like `let counter++` because `let` is a shell builtin, not an external command.\n \n ##### For shell commands with no aggregation\n \n If we do need a shell script body but no aggregation, you can do the above but invoking `sh` (this is still POSIX):\n \n ```sh\n find mydir -name '*.mp3' -exec sh -c '\n echo \"Playing ${1%.mp3}\"\n play \"$1\"\n ' sh {} \\;\n ```\n \n This would not be possible without `sh`, because `${1%.mp3}` is a shell construct that `find` can't evaluate by itself. If we had tried to `let counter++` in this loop, we would have found that the value never changes.\n \n Note that using `+` instead of `\\;`, and using an embedded `for file in \"$@\"` loop rather than `\"$1\"`, will not allow aggregating variables. This is because for large lists, `find` will invoke the command multiple times, each time with some chunk of the input.\n \n \n ### Rationale:\n \n `for var in $(find ...)` loops rely on word splitting and will evaluate globs, which will wreck havoc with filenames containing whitespace or glob characters.\n \n `find -exec` `for i in glob` and `find`+`while` do not rely on word splitting, so they avoid this problem.\n \n ### Exceptions\n \n If you know about and carefully apply `IFS=$'\\n'` and `set -f`, you could choose to ignore this message.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Iterating over ls output is fragile. Use globs. [SC2045]"},{"from": "gpt", "value": "## Iterating over ls output is fragile. Use globs.\n \n ### Problematic code:\n \n ```sh\n for f in $(ls *.wav)\n do\n echo \"$f\"\n done\n ```\n \n ### Correct code:\n \n ```sh\n for f in *.wav\n do\n [[ -e \"$f\" ]] || break # handle the case of no *.wav files\n echo \"$f\"\n done\n ```\n \n Also note that in Bash, `shopt -s nullglob` will allow the loop to run 0 times instead of 1 if there are no matches. There are also [several other conditions](http://mywiki.wooledge.org/BashPitfalls#for_i_in_.24.28ls_.2A.mp3.29) to be aware of.\n \n ### Rationale:\n \n When looping over a set of files, it's always better to use globs when possible. Using command expansion causes word splitting and glob expansion, which will cause problems for certain filenames (typically first seen when trying to process a file with spaces in the name).\n \n The following files can or will break the first loop:\n \n ```sh\n touch 'filename with spaces.wav'\n touch 'filename with * globs.wav'\n touch 'More_Globs[2003].wav'\n touch 'files_with_fønny_chæracters_in_certain_locales.wav'\n ```\n \n ### Related resources:\n \n * [Bash Pitfalls: for i in $(ls *.mp3)](http://mywiki.wooledge.org/BashPitfalls#pf1)\n + [How to loop over directories in Linux?](https://stackoverflow.com/questions/2107945/how-to-loop-over-directories-in-linux)\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Quote this to prevent word splitting. [SC2046]"},{"from": "gpt", "value": "## Quote this to prevent word splitting.\n \n ### Problematic code:\n \n ```sh\n ls -l $(getfilename)\n ```\n \n ### Correct code:\n \n ```sh\n # getfilename outputs 1 file\n ls -l \"$(getfilename)\"\n \n # getfilename outputs multiple files, linefeed separated\n getfilename | while IFS='' read -r line\n do\n ls -l \"$line\"\n done\n ```\n \n ### Rationale:\n \n When command expansions are unquoted, word splitting and globbing will occur. This often manifests itself by breaking when filenames contain spaces.\n \n Trying to fix it by adding quotes or escapes to the data will not work. Instead, quote the command substitution itself.\n \n If the command substitution outputs multiple pieces of data, use a loop instead.\n \n ### Exceptions\n \n In rare cases you actually want word splitting, such as in\n \n ```sh\n # shellcheck disable=SC2046\n gcc $(pkg-config --libs openssl) client.c\n ```\n \n This is because `pkg-config` outputs `-lssl -lcrypto`, which you want to break up by spaces into `-lssl` and `-lcrypto`.\n \n A bash alternative in these cases is to use `read -a` for words or `mapfile` for lines. ksh can also use `read -a`, or a `while read` loop for lines. In this case, since `pkg-config` outputs words, you could use:\n \n ```sh\n # Read words from one line into an array in bash and ksh, then expand each as args\n read -ra args < <(pkg-config --libs openssl)\n gcc \"${args[@]}\" client.c # expand as args\n \n # Read lines into an array, then expand each as args\n readarray -t file_args < <(find /etc/ -type f | grep some-check)\n your-linter.sh \"${file_args[@]}\" # expand as args\n ```\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Use `\"$@\"` (with quotes) to prevent whitespace problems. [SC2048]"},{"from": "gpt", "value": "## Use `\"$@\"` (with quotes) to prevent whitespace problems.\n \n Or: Use \"${array[@]}\" (with quotes) to prevent whitespace problems.\n \n ### Problematic code:\n \n ```sh\n cp $* ~/dir\n cp ${array[*]} ~/dir\n ```\n \n ### Correct code:\n \n ```sh\n cp \"$@\" ~/dir\n cp \"${array[@]}\" ~/dir\n ```\n \n ### Rationale:\n \n `$*` and `${array[*]}`, unquoted, is subject to word splitting and globbing.\n \n Let's say you have three arguments or array elements: `baz`, `foo bar` and `*`\n \n `\"$@\"` and `\"${array[@]}\" `will expand into exactly that: `baz`, `foo bar` and `*`\n \n `$*` and `${array[*]}` will expand into multiple other arguments: `baz`, `foo`, `bar`, `file.txt` and `otherfile.jpg`\n \n Since the latter is rarely expected or desired, ShellCheck warns about it.\n \n ### Exceptions\n \n None.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: `=~` is for regex, but this looks like a glob. Use `=` instead. [SC2049]"},{"from": "gpt", "value": "## `=~` is for regex, but this looks like a glob. Use `=` instead.\n \n ### Problematic code:\n \n ```sh\n [[ $file =~ *.txt ]]\n ```\n \n ### Correct code:\n \n ```sh\n [[ $file = *.txt ]]\n ```\n \n ### Rationale:\n \n You are using `=~` to match against a regex -- specifically a Extended Regular Expression (ERE) -- but the right-hand side looks more like a glob:\n \n * It may have a leading `*`, like in `*.txt`\n * In a glob, this matches strings ending in `.txt`, like `readme.txt` but not `foo.sh`\n * In an ERE, this matches a literal asterisk, followed by any character, and then `txt`, such as `*itxt` but not `test.txt`\n \n * It may be a single letter followed by a `*`, like in `s*`. \n * In a glob, this matches strings starting with `s`, such as `shell` and `set`.\n * In an ERE, this matches zero or more `s`s, such as `dog` (because it does in fact contain zero or more `s`'s)\n \n Please ensure that the pattern is correct as an ERE, or switch to glob matching if that's what you intended.\n \n This is similar to [[SC2063]], where `grep \"*foo*\"` produces an equivalent warning.\n \n ### Exceptions:\n \n If you are aware of the difference, you can [[ignore]] this message, but this warning is not emitted for the more probable EREs `\\*.txt`, `\\.txt$`, `^s` or `s+`, so it should rarely be necessary.\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: This expression is constant. Did you forget the `$` on a variable? [SC2050]"},{"from": "gpt", "value": "## This expression is constant. Did you forget the `$` on a variable?\n ### Problematic code:\n \n ```sh\n if [ myvar = \"test\" ]\n then\n echo \"Test mode\"\n fi\n ```\n \n ### Correct code:\n \n ```sh\n if [ \"$myvar\" = \"test\" ]\n then\n echo \"Test mode\"\n fi\n ```\n ### Rationale:\n \n ShellCheck has found a `[ .. ]` or `[[ .. ]]` comparison that only involves literal strings. The intention was probably to check a variable or command output instead.\n \n This is usually due to missing `$` or bad quoting:\n \n if [[ \"myvar\" = \"test\" ]] # always false because myvar is a literal string\n if [[ \"$myvar\" = \"test\" ]] # correctly compares a variable\n \n if [ 'grep -c foo bar' -ge 10 ] # always false because grep doesn't run\n if [ \"$(grep -c foo bar)\" -ge 10 ] # correctly checks grep output\n \n ### Exceptions:\n \n None\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Bash doesn't support variables in brace range expansions. [SC2051]"},{"from": "gpt", "value": "## Bash doesn't support variables in brace range expansions.\n \n ### Problematic code:\n \n ```bash\n for i in {1..$n}\n do\n echo \"$i\"\n done\n ```\n \n ### Correct code:\n \n ```bash\n for ((i=1; i <= n; i++))\n do\n echo \"$i\"\n done\n ```\n \n ### Rationale:\n \n In Bash, brace expansion happens before variable expansion. This means that brace expansion will not account for variables.\n \n For integers, use an arithmetic for loop instead. For zero-padded numbers or letters, use of eval may be warranted:\n \n ```bash\n from=\"a\" to=\"m\"\n for c in $(eval \"echo {$from..$to}\"); do echo \"$c\"; done\n ```\n \n or more carefully (if `from`/`to` could be user input, or if the brace expansion could have spaces):\n \n ```bash\n from=\"a\" to=\"m\"\n while IFS= read -d '' -r c\n do\n echo \"Read $c\"\n done < <(eval \"printf '%s\\0' $(printf \"{%q..%q}.jpg\" \"$from\" \"$to\")\")\n ```\n \n ### Exceptions\n \n None (if you're writing for e.g. zsh, you can use a directive to disable this check)\n \n ### Related Resources:\n \n * [StackOverflow: Variables in bash seq replacement ({1..10})](https://stackoverflow.com/questions/169511/how-do-i-iterate-over-a-range-of-numbers-defined-by-variables-in-bash)\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Quote the rhs of `=` in `[[ ]]` to prevent glob matching. [SC2053]"},{"from": "gpt", "value": "## Quote the rhs of `=` in `[[ ]]` to prevent glob matching.\n \n ### Problematic code:\n \n ```sh\n [[ $a = $b ]]\n ```\n \n ### Correct code:\n \n ```sh\n [[ $a = \"$b\" ]]\n ```\n ### Rationale:\n \n When the right-hand side of `=`, `==` or `!=` is unquoted in `[[ .. ]]`, it will be treated like a glob.\n \n This has some unexpected consequences like `[[ $var = $var ]]` being false (for `var='[a]'`), or `[[ $foo = $bar ]]` giving a different result from `[[ $bar = $foo ]]`.\n \n The most common intention is to compare one variable to another as strings, in which case the right-hand side must be quoted.\n \n ### Exceptions:\n \n If you explicitly want to match against a pattern, you can [[ignore]] this warning.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Use spaces, not commas, to separate array elements. [SC2054]"},{"from": "gpt", "value": "## Use spaces, not commas, to separate array elements.\n \n ### Problematic code:\n \n ```sh\n flags=(\"-l\", \"-d\", \"--sort=size\")\n ls \"${flags[@]}\"\n ```\n \n ### Correct code:\n \n ```sh\n flags=(\"-l\" \"-d\" \"--sort=size\")\n ls \"${flags[@]}\"\n ```\n ### Rationale:\n \n You appear to have used commas to separate array elements in an array assignment. Other languages require this, but bash instead treats the commas as literal strings.\n \n In the problematic code, the first element is `-l,` with the trailing comma, and the executed command ends up being `ls -l, -d, --sort=size`.\n \n In the correct code, the trailing commas have been removed, and the command will be `ls -l -d --sort=size` as expected.\n \n ### Exceptions:\n \n None (if you actually want a trailing comma in your strings, move them inside the quotes).\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: You probably wanted `&&` here, otherwise it's always true. [SC2055]"},{"from": "gpt", "value": "## You probably wanted `&&` here, otherwise it's always true.\n \n ### Problematic code:\n \n ```sh\n if [[ $1 != foo || $1 != bar ]]\n then\n echo \"$1 is not foo or bar\"\n fi\n ```\n \n ### Correct code:\n \n ```sh\n if [[ $1 != foo && $1 != bar ]]\n then\n echo \"$1 is not foo or bar\"\n fi\n ```\n \n ### Rationale:\n \n This is not a bash issue, but a simple, common logical mistake applicable to all languages.\n \n `[[ $1 != foo || $1 != bar ]]` is always true (when `foo != bar`):\n \n * If `$1 = foo` then `$1 != bar` is true, so the statement is true.\n * If `$1 = bar` then `$1 != foo` is true, so the statement is true.\n * If `$1 = cow` then `$1 != foo` is true, so the statement is true.\n \n `[[ $1 != foo && $1 != bar ]]` matches when `$1` is neither `foo` nor `bar`:\n \n * If `$1 = foo`, then `$1 != foo` is false, so the statement is false.\n * If `$1 = bar`, then `$1 != bar` is false, so the statement is false.\n * If `$1 = cow`, then both `$1 != foo` and `$1 != bar` is true, so the statement is true.\n \n This statement is identical to `! [[ $1 = foo || $1 = bar ]]`, which also works correctly.\n \n ### Exceptions\n \n Rare.\n \n * If I want to check that $FOO, $BAR and $COW are all equal:\n ```sh\n if [[ $FOO != $BAR || $FOO != $COW ]]\n then\n echo \"$FOO and $BAR and $COW are not all equal\"\n fi\n ```\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: You probably wanted `&&` here [SC2056]"},{"from": "gpt", "value": "## You probably wanted `&&` here\n \n ### Problematic code:\n \n ```sh\n if (( $1 != 0 || $1 != 3 ))\n then\n echo \"$1 is not 0 or 3\"\n fi\n ```\n \n ### Correct code:\n \n ```sh\n if (( $1 != 0 && $1 != 3 ))\n then\n echo \"$1 is not 0 or 3\"\n fi\n ```\n \n ### Rationale:\n \n This is not a bash issue, but a simple, common logical mistake applicable to all languages.\n \n `(( $1 != 0 || $1 != 3 ))` is always true:\n \n * If `$1 = 0` then `$1 != 3` is true, so the statement is true.\n * If `$1 = 3` then `$1 != 0` is true, so the statement is true.\n * If `$1 = 42` then `$1 != 0` is true, so the statement is true.\n \n `(( $1 != 0 && $1 != 3 ))` is true only when `$1` is not `0` and not `3`:\n \n * If `$1 = 0`, then `$1 != 3` is false, so the statement is false.\n * If `$1 = 3`, then `$1 != 0` is false, so the statement is false.\n * If `$1 = 42`, then both `$1 != 0` and `$1 != 3` is true, so the statement is true.\n \n This statement is identical to `! (( $1 == 0 || $1 == 3 ))`, which also works correctly.\n \n ### Exceptions\n \n None.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Unknown binary operator. [SC2057]"},{"from": "gpt", "value": "## Unknown binary operator.\n \n ### Problematic code:\n \n ```sh\n [ \"$var\" -leq 42 ]\n ```\n \n ### Correct code:\n \n ```sh\n [ \"$var\" -le 42 ]\n ```\n \n ### Rationale:\n \n You are using an unknown binary operator in a `test` expression. Choose one that exists.\n \n In bash, use `help test` to see a list of supported operators:\n \n FILE1 -nt FILE2 True if file1 is newer than file2 (according to\n modification date).\n \n FILE1 -ot FILE2 True if file1 is older than file2.\n \n FILE1 -ef FILE2 True if file1 is a hard link to file2.\n \n STRING1 = STRING2\n True if the strings are equal.\n STRING1 != STRING2\n True if the strings are not equal.\n STRING1 < STRING2\n True if STRING1 sorts before STRING2 lexicographically.\n STRING1 > STRING2\n True if STRING1 sorts after STRING2 lexicographically.\n \n arg1 OP arg2 Arithmetic tests. OP is one of -eq, -ne,\n -lt, -le, -gt, or -ge.\n \n Arithmetic binary operators return true if ARG1 is equal, not-equal,\n less-than, less-than-or-equal, greater-than, or greater-than-or-equal\n than ARG2.\n \n \n ### Exceptions:\n \n None. If you've tested and verified that the operator works but the latest version of ShellCheck says it's unknown, please [submit a bug report](https://github.com/koalaman/shellcheck/issues).\n \n ### Related resources:\n \n * [The classic test command](http://wiki.bash-hackers.org/commands/classictest) on the Bash Hackers wiki.\n * [The conditional expression](http://wiki.bash-hackers.org/syntax/ccmd/conditional_expression) on the Bash Hackers wiki.\n * [Tests and conditionals](https://mywiki.wooledge.org/BashGuide/TestsAndConditionals) on the Wooledge BashGuide.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Unknown unary operator. [SC2058]"},{"from": "gpt", "value": "## Unknown unary operator.\n \n ### Problematic code:\n \n ```sh\n [ -E 42 ]\n ```\n \n ### Correct code:\n \n ```sh\n [ -e 42 ]\n ```\n \n ### Rationale:\n \n You are using an unknown unary operator in a `test` expression. Perhaps it's a typo?\n \n In bash, you can use `help test` to see a list of supported operators:\n \n -a FILE True if file exists.\n -b FILE True if file is block special.\n -c FILE True if file is character special.\n -d FILE True if file is a directory.\n -e FILE True if file exists.\n -f FILE True if file exists and is a regular file.\n -g FILE True if file is set-group-id.\n -h FILE True if file is a symbolic link.\n -L FILE True if file is a symbolic link.\n -k FILE True if file has its `sticky' bit set.\n -p FILE True if file is a named pipe.\n -r FILE True if file is readable by you.\n -s FILE True if file exists and is not empty.\n -S FILE True if file is a socket.\n -t FD True if FD is opened on a terminal.\n -u FILE True if the file is set-user-id.\n -w FILE True if the file is writable by you.\n -x FILE True if the file is executable by you.\n -O FILE True if the file is effectively owned by you.\n -G FILE True if the file is effectively owned by your group.\n -N FILE True if the file has been modified since it was last read.\n \n ### Exceptions:\n \n None. If you've tested and verified that the operator works but the latest version of ShellCheck says it's unknown, please [submit a bug report](https://github.com/koalaman/shellcheck/issues).\n \n ### Related resources:\n \n * [The classic test command](http://wiki.bash-hackers.org/commands/classictest) on the Bash Hackers wiki.\n * [The conditional expression](http://wiki.bash-hackers.org/syntax/ccmd/conditional_expression) on the Bash Hackers wiki.\n * [Tests and conditionals](https://mywiki.wooledge.org/BashGuide/TestsAndConditionals) on the Wooledge BashGuide.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Don't use variables in the `printf` format string. Use `printf \"..%s..\" \"$foo\"`. [SC2059]"},{"from": "gpt", "value": "# Don't use variables in the `printf` format string. Use `printf \"..%s..\" \"$foo\"`.\n \n ### Problematic code:\n \n ```sh\n printf \"Hello, $NAME\\n\"\n ```\n \n ### Correct code:\n \n ```sh\n printf \"Hello, %s\\n\" \"$NAME\"\n ```\n \n ### Rationale:\n \n `printf` interprets escape sequences and format specifiers in the format string. If variables are included, any escape sequences or format specifiers in the data will be interpreted too, when you most likely wanted to treat it as data. Example:\n \n ```sh\n coverage='96%'\n printf \"Unit test coverage: %s\\n\" \"$coverage\"\n printf \"Unit test coverage: $coverage\\n\"\n ```\n \n The first printf writes `Unit test coverage: 96%`.\n \n The second writes ``bash: printf: `\\': invalid format character``\n \n Sometimes you may actually want to interpret data as a format string, like in:\n \n ```sh\n octToAscii() { printf \"\\\\$1\"; }\n octToAscii 130\n ```\n \n In this case, use the `%b` format specifier that expands escape sequences without interpreting other format specifiers:\n \n ```sh\n octToAscii() { printf '%b' \"\\0$1\"; }\n octToAscii 130\n ```\n \n ### Exceptions:\n \n Sometimes you might have a pattern in a variable:\n \n ```sh\n filepattern=\"file-%d.jpg\"\n printf -v filename \"$filepattern\" \"$number\"\n ```\n \n This has no good rewrite. Please [[ignore]] the warning with a [[directive]].\n \n ### Related resources:\n \n * https://pubs.opengroup.org/onlinepubs/9799919799/utilities/printf.html\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Quote parameters to `tr` to prevent glob expansion. [SC2060]"},{"from": "gpt", "value": "# Quote parameters to `tr` to prevent glob expansion.\n \n ### Problematic code:\n \n ```sh\n tr -cd [:digit:]\n ```\n \n ### Correct code:\n \n ```sh\n tr -cd '[:digit:]'\n ```\n \n ### Rationale:\n \n From the shell's point of view, unquoted `[:digit:]` is a glob equivalent to `[digit:]` that matches any single character filename from the group, such as `d` or `t`, in the current directory. \n \n If someone starts learning D and creates a directory named `d` to hold the source code, the glob will be expanded and the script will end up executing `tr -cd d` instead, which is clearly unintended.\n \n Quoting the argument prevents this, and will pass it correctly as the literal string `[:digit:]` no matter which files exist in the current directory.\n \n ### Exceptions\n \n None\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Quote the parameter to `-name` so the shell won't interpret it. [SC2061]"},{"from": "gpt", "value": "## Quote the parameter to `-name` so the shell won't interpret it.\n \n ### Problematic code:\n \n ```sh\n find . -name *.txt\n ```\n \n ### Correct code:\n \n ```sh\n find . -name '*.txt'\n ```\n ### Rationale:\n \n Several find options take patterns to match against, including `-ilname`, `-iname`, `-ipath`, `-iregex`, `-iwholename`, `-lname`, `-name`, `-path`, `-regex` and `-wholename`.\n \n These compete with the shell's pattern expansion, and must therefore be quoted so that they are passed literally to `find`.\n \n The example command may end up executing as `find . -name README.txt` after the shell has replaced the `*.txt` with a matching file `README.txt` from the current directory. \n \n This may happen today or suddenly in the future.\n \n ### Exceptions:\n \n None.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Quote the grep pattern so the shell won't interpret it. [SC2062]"},{"from": "gpt", "value": "# Quote the grep pattern so the shell won't interpret it.\n \n ### Problematic code\n grep foo* file\n \n ### Correct code\n grep \"foo*\" file\n \n ### Rationale\n The regex passed to grep frequently contains characters that collide with globs. The code above is supposed to match \"f followed by 1 or more o's\", but if the directory contains a file called \"foo.txt\", an unquoted pattern will cause it to become `grep foo.txt file`.\n \n To prevent this, always quote the regex passed to grep, especially when it contains one or more glob character.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Grep uses regex, but this looks like a glob. [SC2063]"},{"from": "gpt", "value": "## Grep uses regex, but this looks like a glob.\n \n ### Problematic code:\n \n ```sh\n grep '*foo*'\n ```\n \n ### Correct code:\n \n ```sh\n grep 'foo' # or more explicitly, grep '.*foo.*'\n ```\n \n ### Rationale:\n \n In globs, `*` matches any number of any character.\n \n In regex, `*` matches any number of the preceding character.\n \n `grep` uses regex, not globs, so this means that `grep '*foo'` is nonsensical because there's no preceding character for `*`.\n \n If the intention was to match \"any number of characters followed by foo\", use `'.*foo'`. Also note that since grep matches substrings, this will match \"fishfood\". Use anchors to prevent this, e.g. `foo$`.\n \n This also means that `f*` will match \"hello\", because `f*` matches 0 (or more) \"f\"s and there are indeed 0 \"f\" characters in \"hello\". Again, use `grep 'f'` to find strings containing \"f\", or `grep '^f'` to find strings starting with \"f\".\n \n \n ### Exceptions\n \n If you're aware of the differences between globs and regex, you can ignore this message.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Use single quotes, otherwise this expands now rather than when signalled. [SC2064]"},{"from": "gpt", "value": "## Use single quotes, otherwise this expands now rather than when signalled.\n \n ### Problematic code:\n \n ```sh\n trap \"echo \\\"Finished on $(date)\\\"\" EXIT\n trap \"rm -fr '$testdir1' '$testdir2'\" $TRAP_SIGNALS\n trap \"rm $tmp\" $TRAP_SIGNALS\n trap \"${remove_aar_temp}\" SIGKILL SIGTERM SIGQUIT EXIT\n trap \"$(shopt -p extglob)\" RETURN\n ```\n \n ### Correct code:\n \n ```sh\n trap 'echo \"Finished on $(date)\"' EXIT\n ```\n \n ### Rationale:\n \n With double quotes, all parameter and command expansions will expand when the trap is defined rather than when it's executed.\n \n In the example with the Problematic code, the message will contain the date on which the trap was declared, and not the date on which the script exits.\n \n Using single quotes will prevent expansion at declaration time, and save it for execution time.\n \n ### Exceptions\n \n If you don't care that the trap code is expanded early because the commands/variables won't change during execution of the script, or because you want to use the current and not the future values, then you can ignore this message.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: This is interpreted as a shell file redirection, not a comparison. [SC2065]"},{"from": "gpt", "value": "## This is interpreted as a shell file redirection, not a comparison.\n \n ### Problematic code:\n \n ```sh\n [ 1 >2 ] || [ 3>'aaa bb' ] # Simple example of problematic code\n ```\n \n ### Correct code:\n \n ```sh\n [ 1 -gt 2 ] || [ 3 \\> 'aaa bb' ] # arithmetical, lexicographical\n ```\n ### Rationale:\n \n A word that looks like a redirection in simple shell commands causes it to be interpreted as a redirection.\n ShellCheck would guess that you don't want it in tests.\n \n ### Exceptions:\n \n When it's among a continuous list of redirections at the end of a simple `test` command, it's more likely that\n the user really meant to do a redirection. Or any other case that you mean to do that.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Since you double-quoted this, it will not word split, and the loop will only run once. [SC2066]"},{"from": "gpt", "value": "## Since you double-quoted this, it will not word split, and the loop will only run once.\n \n ### Problematic code:\n \n ```sh\n for s in \"$(mycommand)\"; do echo \"$s\"; done\n ```\n \n ### Correct code:\n \n The correct code depends on your intention. Let's say you're in a directory with the files `file.png` and `My cat.png`, and you want to loop over a command that outputs (or variable that contains):\n \n ```sh\n hello world\n My *.png\n ```\n \n #### Loop over each line without globbing (`hello world`, `My *.png`)\n \n ```sh\n mycommand | while IFS= read -r s; do echo \"$s\"; done\n ```\n \n #### Loop over each word with globbing (`hello`, `world`, `My`, `file.png`, `My cat.png`):\n \n ```sh\n # relies on the fact that IFS by default contains space-tab-linefeed\n for s in $(mycommand); do echo \"$s\"; done\n ```\n \n #### Loop over each line with globbing (`hello world`, `My cat.png`)\n \n ```sh\n # explicitly set IFS to contain only a line feed\n IFS='\n '\n for s in $(mycommand); do echo \"$s\"; done\n ```\n \n ### Rationale:\n \n You get this warning because you have a loop that will only ever run exactly one iteration. Since you have a loop, you clearly expect it to run more than once. You just have to decide how it should be split up.\n \n ### Exceptions\n \n None.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Missing `;` or `+` terminating `-exec`. You can't use `|`/`||`/`&&`, and `;` has to be a separate, quoted argument. [SC2067]"},{"from": "gpt", "value": "## Missing `;` or `+` terminating `-exec`. You can't use `|`/`||`/`&&`, and `;` has to be a separate, quoted argument.\n \n ### Problematic code:\n \n ```sh\n find . -type f -exec shellcheck {} | wc -l \\;\n find . -exec echo {} ;\n ```\n \n ### Correct code:\n \n ```sh\n find . -type f -exec sh -c 'shellcheck \"$1\" | wc -l' -- {} \\;\n find . -exec echo {} \\;\n ```\n \n ### Rationale:\n \n `find -exec` is still subject to all normal shell rules, so all shell features like `|`, `||`, `&` and `&&` will apply to the `find` command itself, and not to the command you are trying to construct with `-exec`.\n \n `find . -exec foo {} && bar {} \\;` means run the command `find . -exec foo {}`, and if find is successful, run the command `bar \"{}\" \";\"`.\n \n To instead go through each file and run `foo file && bar file` on it, invoke a shell that can interpret `&&`:\n \n ```sh\n find . -exec sh 'foo \"$1\" && bar \"$1\"' -- {} \\;\n ```\n \n You can also use find `-a` instead of shell `&&`:\n \n ```sh\n find . -exec foo {} \\; -a -exec bar {} \\;\n ```\n \n This will have the same effect (`-a` is also the default when two commands are specified, and can therefore be omitted).\n \n ### Exceptions\n \n None\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Double quote array expansions to avoid re-splitting elements. [SC2068]"},{"from": "gpt", "value": "## Double quote array expansions to avoid re-splitting elements.\n \n ### Problematic code:\n \n ```sh\n cp $@ ~/dir\n ```\n \n ### Correct code:\n \n ```sh\n cp \"$@\" ~/dir\n ```\n \n ### Rationale:\n \n Double quotes around `$@` (and similarly, `${array[@]}`) prevents globbing and word splitting of individual elements, while still expanding to multiple separate arguments.\n \n Let's say you have four arguments: `baz`, `foo bar`, `*` and `/*/*/*/*`\n \n `\"$@\"` will expand into exactly that: `baz`, `foo bar`, `*` and `/*/*/*/*`\n \n `$@` will expand into multiple other arguments: `baz`, `foo`, `bar`, `file.txt`, `otherfile.jpg`, and (eventually) a list of most files on the system\n \n Since the latter is rarely expected or desired, ShellCheck warns about it.\n \n ### Exceptions\n \n When you want globbing of individual elements.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: To redirect stdout+stderr, `2>&1` must be last (or use `{ cmd > file; } 2>&1` to clarify). [SC2069]"},{"from": "gpt", "value": "## To redirect stdout+stderr, `2>&1` must be last (or use `{ cmd > file; } 2>&1` to clarify).\n \n ### Problematic code:\n \n ```sh\n firefox 2>&1 > /dev/null\n ```\n \n ### Correct code:\n \n ```sh\n firefox > /dev/null 2>&1\n ```\n \n ### Rationale:\n \n When it comes to redirection, order matters.\n \n The problematic code means \"Point stderr to where stdout is currently pointing (the terminal). Then point stdout to /dev/null\".\n \n The correct code means \"Point stdout to /dev/null. Then point stderr to where stdout is currently pointing (/dev/null)\".\n \n In other words, the problematic code hides stdout and shows stderr. The correct code hides both stderr and stdout, which is usually the intention.\n \n ### Exceptions\n \n If you actually do want to redirect stdout to a file, and then turn stderr into the new stdout, you can make this more explicit with braces:\n \n { firefox > /dev/null; } 2>&1\n \n Also note that this warning does not trigger when output is piped or captured.\n \n ### Related resources:\n \n * [Bash Pitfalls: somecmd 2>&1 >>logfile](https://mywiki.wooledge.org/BashPitfalls#pf43)\n * [BashFaq: Tell me all about 2>&1 -- what's the difference between 2>&1 >foo and >foo 2>&1, and when do I use which?](https://mywiki.wooledge.org/BashFAQ/055)\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: `-n` doesn't work with unquoted arguments. Quote or use `[[ ]]`. [SC2070]"},{"from": "gpt", "value": "## `-n` doesn't work with unquoted arguments. Quote or use `[[ ]]`.\n \n ### Problematic code:\n \n ```sh\n if [ -n $var ]\n then\n echo \"var has a value\"\n else\n echo \"var is empty\"\n fi\n ```\n \n ### Correct code:\n \n In POSIX:\n \n ```sh\n if [ -n \"$var\" ]\n then\n echo \"var has a value\"\n else\n echo \"var is empty\"\n fi\n ```\n \n In bash/ksh:\n \n ```sh\n if [[ -n $var ]]\n then\n echo \"var has a value\"\n else\n echo \"var is empty\"\n fi\n ```\n \n \n ### Rationale:\n \n When `$var` is unquoted, a blank value will cause it to wordsplit and disappear. If `$var` is empty, these two statements are identical:\n \n ```sh\n [ -n $var ]\n [ -n ]\n ```\n \n `[ string ]` is shorthand for testing if a string is empty. This is still true if `string` happens to be `-n`. `[ -n ]` is therefore true, and by extension so is `[ -n $var ]`.\n \n To fix this, either quote the variable, or (if your shell supports it) use `[[ -n $var ]]` which generally has fewer caveats than `[`.\n \n ### Exceptions:\n \n None\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: `>` is for string comparisons. Use `-gt` instead. [SC2071]"},{"from": "gpt", "value": "## `>` is for string comparisons. Use `-gt` instead.\n \n ### Problematic code:\n \n ```sh\n if [[ $var > 10 ]]\n then\n echo \"Incorrectly triggers when var=5\"\n fi\n ```\n \n ### Correct code:\n \n ```sh\n if [[ $var -gt 10 ]]\n then\n echo \"Correct numerical comparison\"\n fi\n ```\n ### Rationale:\n \n `<` and `>`, in both `[[` and `[` (when escaped) will do a lexicographical comparison, not a numerical comparison. \n \n This means that `[[ 5 > 10 ]]` is true because 5 comes after 10 alphabetically. Meanwhile `[[ 5 -gt 10 ]]` is false because 5 does not come after 10 numerically.\n \n If you want to compare numbers by value, use the numerical comparison operators `-gt`, `-ge`, `-lt` and `-le`.\n \n ### Exceptions:\n \n If the strings happen to be version numbers and you're using <, or > to compare them as strings, and you consider this an acceptable thing to do, then you can ignore this warning.\n \n ### Related resources:\n \n * [Bash Pitfalls: `[[ $foo > 7 ]]`](https://mywiki.wooledge.org/BashPitfalls#pf7)\n * [StackOverflow: Comparing numbers in Bash](https://stackoverflow.com/questions/18668556/comparing-numbers-in-bash)\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Decimals are not supported. Either use integers only, or use `bc` or `awk` to compare. [SC2072]"},{"from": "gpt", "value": "## Decimals are not supported. Either use integers only, or use `bc` or `awk` to compare.\n \n ### Problematic code:\n \n ```sh\n [[ 2 -lt 3.14 ]]\n ```\n \n ### Correct code:\n \n ```sh\n [[ 200 -lt 314 ]] # Use fixed point math\n [[ $(echo \"2 < 3.14\" | bc) == 1 ]] # Use bc\n ```\n \n ### Rationale:\n \n Bash and Posix sh does not support decimals in numbers. Decimals should either be avoided, or compared using a tool that does support them.\n \n ### Exceptions\n \n If the strings happen to be version numbers and you're using `<`, or `>` to compare them as strings, and you consider this an acceptable thing to do, then you can ignore this warning.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Escape `\\<` to prevent it redirecting (or switch to `[[ .. ]]`). [SC2073]"},{"from": "gpt", "value": "## Escape `\\<` to prevent it redirecting (or switch to `[[ .. ]]`).\n \n ### Problematic code:\n \n ```sh\n if [ \"aardvark\" < \"zebra\" ]\n then\n echo \"Alphabetical!\"\n fi\n ```\n \n ### Correct code:\n \n ```sh\n if [ \"aardvark\" \\< \"zebra\" ]\n then\n echo \"Alphabetical!\"\n fi\n ```\n \n or optionally in Bash/Ksh:\n \n ```sh\n if [[ \"aardvark\" < \"zebra\" ]]\n then\n echo \"Alphabetical!\"\n fi\n ```\n ### Rationale:\n \n You are using the operator `<` or `>` in a `[` test expression.\n \n In this context, it will be considered a file redirection operator instead, so `[ \"aardvark\" < \"zebra\" ]` is equivalent to `[ \"aardvark\" ] < ./zebra`, which is true if there exists a readable file `zebra` in the current directory.\n \n If you wanted to compare two strings lexicographically (alphabetically), escape the `<` or `>` with a backslash as in the correct example. \n \n If you want to compare two numbers numerically, use `-lt` or `-ge` instead.\n \n ### Exceptions:\n \n None.\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Can't use `=~` in `[ ]`. Use `[[..]]` instead. [SC2074]"},{"from": "gpt", "value": "## Can't use `=~` in `[ ]`. Use `[[..]]` instead.\n \n ### Problematic code:\n \n ```sh\n [ \"$input\" =~ DOC[0-9]*\\.txt ] && echo \"match\"\n ```\n \n ### Correct code:\n \n ```sh\n [[ \"$input\" =~ DOC[0-9]*\\.txt ]] && echo \"match\"\n ```\n ### Rationale:\n \n `=~` only works in `[[ .. ]]` tests. It does not work with `test` or `[` in any shell.\n \n If you're targeting POSIX `sh`, rewrite in terms of `case` or `grep` instead.\n \n ### Exceptions:\n \n None.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Escaping `\\<` is required in `[..]`, but invalid in `[[..]]` [SC2075]"},{"from": "gpt", "value": "## Escaping `\\<` is required in `[..]`, but invalid in `[[..]]`\n \n ### Problematic code:\n \n ```sh\n [[ aardvark \\< zebra ]]\n ```\n \n ### Correct code:\n \n ```sh\n [[ aardvark < zebra ]]\n ```\n \n ### Rationale:\n \n Grammatically speaking, `[` is considered a normal command name, so `<` and `>` are interpreted as redirections. When using the lexicographical string operators `<` and `>` in `[ .. ]`, they must be escaped (e.g. `\\<` or `\"<\"`).\n \n `[[` is considered its own grammatical construct, and therefore it does not require (nor does it allow) escaping `<` or `>`. \n \n ### Exceptions:\n \n None\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Don't quote rhs of `=~`, it'll match literally rather than as a regex. [SC2076]"},{"from": "gpt", "value": "## Don't quote rhs of `=~`, it'll match literally rather than as a regex.\n \n ### Problematic code:\n \n ```sh\n [[ $foo =~ \"^fo+ bar$\" ]]\n ```\n \n ### Correct code:\n \n ```sh\n [[ $foo =~ ^fo+\\ bar$ ]]\n ```\n \n ### Rationale:\n \n Quotes on the right hand side of `=~` can be used to match literally, so that `[[ $1 =~ ^\"$2\".* ]]` works even if `$2` contains regex metacharacters. This mirrors the behavior of globs, `[[ $1 = \"$2\"* ]]`.\n \n This also means that the problematic code tries to match literal carets and plus signs instead of interpreting them as regular expression matchers. To match as a regex, the regex metacharacters it must be unquoted. Literal parts of the expression can be quoted with double or single quotes, or escaped.\n \n ### Exceptions:\n \n If you do want to match literally just to do a plain substring search, e.g. `[[ $foo =~ \"bar\" ]]`, you could ignore this message, but consider using a more canonical glob match instead: `[[ $foo == *\"bar\"* ]]`.\n \n ### Compatibility:\n \n * In Bash 3.2 and newer with shopt `compat31` *disabled (the default)*, quoted patterns are literal whereas unquoted patterns are parsed for regex metacharacters.\n * In Bash 3.2 and newer with shopt `compat31` *enabled*, quoted and unquoted patterns match identically.\n * In Bash 3.1 quoted and unquoted patterns match identically.\n \n See http://stackoverflow.com/questions/218156/bash-regex-with-quotes\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: You need spaces around the comparison operator. [SC2077]"},{"from": "gpt", "value": "## You need spaces around the comparison operator.\n \n ### Problematic code:\n \n ```sh\n [[ 0=1 ]]\n ```\n \n ### Correct code:\n \n ```sh\n [[ 0 = 1 ]]\n ```\n \n ### Rationale:\n \n `[[ 0 = 1 ]]` means \"check if 0 and 1 are equal\".\n \n `[[ str ]]` is short form for `[[ -n str ]]`, and means \"check if `str` is non-empty\". It doesn't matter if `str` happens to contain `0=1`.\n \n Always use spaces around the comparison operator in `[..]` and `[[..]]`, otherwise it won't be recognized as an operator.\n \n ### Exceptions\n \n None.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: This expression is constant. Did you forget a `$` somewhere? [SC2078]"},{"from": "gpt", "value": "## This expression is constant. Did you forget a `$` somewhere?\n ### Problematic code:\n \n ```sh\n if [ \"myvar\" ]\n then\n echo \"myvar is set\"\n fi\n ```\n \n ### Correct code:\n \n ```sh\n if [ \"$myvar\" ]\n then\n echo \"myvar is set\"\n fi\n ```\n ### Rationale:\n \n ShellCheck has found a `[ .. ]` or `[[ .. ]]` statement that just contains a literal string. Such a check does not do anything useful, and will always be true (or always false, for empty strings).\n \n This is usually due to missing `$` or bad quoting:\n \n if [[ STY ] # always true\n if [[ $STY ]] # checks variable $STY\n \n if [[ 'grep foo bar' ]] # always true\n if [[ `grep foo bar` ]] # checks grep output (poorly)\n if grep -q foo bar # checks for grep match (preferred)\n \n \n ### Exceptions:\n \n None\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: `(( ))` doesn't support decimals. Use `bc` or `awk`. [SC2079]"},{"from": "gpt", "value": "## `(( ))` doesn't support decimals. Use `bc` or `awk`.\n \n Bash [arithmetic conditional evaluation can only be performed on integers](https://www.tldp.org/LDP/abs/html/comparison-ops.html). More detail: Bash has limited data types which [include integer](http://www.tldp.org/LDP/abs/html/declareref.html), but everything is effectively [untyped](http://www.tldp.org/LDP/abs/html/untyped.html).\n \n Suggested workarounds to this constraint use bc or awk, here are \n [some examples](https://stackoverflow.com/questions/11237794/how-to-compare-two-decimal-numbers-in-bash-awk).\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Numbers with leading 0 are considered octal. [SC2080]"},{"from": "gpt", "value": "## Numbers with leading 0 are considered octal.\n \n ### Problematic code:\n \n ```sh\n echo $(( 16 - 08 ))\n ```\n \n ### Correct code:\n \n ```sh\n echo $(( 16 - 8 ))\n ```\n ### Rationale:\n \n ShellCheck found an integer literal with a leading zero, but containing the digits 8 or 9.\n \n This is invalid, as the integer will be interpreted as an octal value (e.g. 0777 == 0x1FF == 511).\n \n To have the value parsed in base 10, either remove the leading zeros as in the example, or specify the radix explicitly:\n \n echo $((10#08)) \n \n ### Exceptions:\n \n None\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n \n [The BASH manual \"Shell Arithmetic\" chapter](https://www.gnu.org/software/bash/manual/html_node/Shell-Arithmetic.html)\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: `[ .. ]` can't match globs. Use `[[ .. ]]` or grep. [SC2081]"},{"from": "gpt", "value": "## `[ .. ]` can't match globs. Use `[[ .. ]]` or grep.\n \n ### Problematic code:\n \n ```sh\n if [ $var == *[^0-9]* ]\n then\n echo \"$var is not numeric\"\n fi \n ```\n \n ### Correct code:\n \n ```sh\n if [[ $var == *[^0-9]* ]]\n then\n echo \"$var is not numeric\"\n fi \n ```\n ### Rationale:\n \n `[ .. ]` aka `test` can not match against globs. \n \n In bash/ksh, you can instead use `[[ .. ]]` which supports this behavior.\n \n In sh, you can rewrite to use `grep`. \n \n ```sh\n if echo $var | grep -q '^[0-9]*$'; then\n echo \"$var is numeric\"\n fi\n ```\n \n ### Exceptions:\n \n None. If you are not trying to match a glob, quote the argument (e.g. `[ $var == '*' ]` to match literal asterisk. \n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: To expand via indirection, use `name=\"foo$n\"; echo \"${!name}\"`. [SC2082]"},{"from": "gpt", "value": "## To expand via indirection, use `name=\"foo$n\"; echo \"${!name}\"`.\n \n ### Problematic code:\n \n ```sh\n var_1=\"hello world\"\n n=1\n echo \"${var_$n}\"\n ```\n \n ### Correct code:\n \n Bash/ksh:\n \n ```sh\n # Use arrays instead of dynamic names\n declare -a var\n var[1]=\"hello world\"\n n=1\n echo \"${var[n]}\"\n ```\n \n or\n \n ```sh\n # Expand variable names dynamically\n var_1=\"hello world\"\n n=1\n name=\"var_$n\"\n echo \"${!name}\"\n ```\n \n POSIX sh:\n \n ```sh\n # Expand dynamically with eval\n var_1=\"hello world\"\n n=1\n eval \"tmp=\\$var_$n\"\n echo \"${tmp}\"\n ```\n \n ### Rationale:\n \n You can expand a variable `var_1` with `${var_1}`, but you can not generate the string `var_1` with an embedded expansion, like `${var_$n}`.\n \n Instead, if at all possible, you should use an array. Bash and ksh support both numerical and associative arrays, and an example is shown above.\n \n If you can't use arrays, you can indirectly reference variables by creating a temporary variable with its name, e.g. `myvar=\"var_$n\"` and then expanding it indirectly with `${!myvar}`. This will give the contents of the variable `var_1`.\n \n If using POSIX sh, where neither arrays nor `${!var}` is available, `eval` can be used. You must be careful in sanitizing the data used to construct the variable name to avoid arbitrary code execution.\n \n ### Exceptions:\n \n None\n \n ### Related resources:\n \n * [BashFaq: How can I use variable variables (indirect variables, pointers, references) or associative arrays?](https://mywiki.wooledge.org/BashFAQ/006)\n * [StackOverflow: Dynamic variable names in Bash](https://stackoverflow.com/questions/16553089/dynamic-variable-names-in-bash)\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Don't add spaces after the slash in `./file`. [SC2083]"},{"from": "gpt", "value": "## Don't add spaces after the slash in `./file`.\n \n ### Problematic code:\n \n ```sh\n gcc -o myfile file.c\n ./ myfile\n ```\n \n ### Correct code:\n \n ```sh\n gcc -o myfile file.c\n ./myfile\n ```\n ### Rationale:\n \n Contrary to popular belief, there is no command or syntax `./` that runs a file.\n \n `./myfile` is simply the shortest path equivalent to `myfile` that specifies a directory and therefore causes a shell to run it as-is, instead of trying to find its directory using $PATH.\n \n Therefore, to run a file in the current directory, use `./myfile` and not `./ myfile`. \n \n ### Exceptions:\n \n None\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Remove `$` or use `_=$((expr))` to avoid executing output. [SC2084]"},{"from": "gpt", "value": "## Remove `$` or use `_=$((expr))` to avoid executing output.\n \n ### Problematic code:\n \n ```sh\n i=4\n $(( i++ ))\n ```\n \n ### Correct code:\n \n Bash, Ksh:\n \n ```sh\n i=4\n (( i++ ))\n ```\n \n POSIX (assuming `++` is supported):\n \n ```sh\n i=4\n _=$(( i++ ))\n ```\n \n Alternative POSIX version that does not preserve the exit code:\n \n ```sh\n : $(( i++ ))\n ```\n \n ### Rationale:\n \n `$((..))` expands to a number. If it's the only word on the line, the shell will try to execute this number as a command name:\n \n ```sh\n $ i=4\n $ $(( i++ ))\n 4: command not found\n $ echo $i\n 5\n ```\n \n To avoid trying to execute the number as a command name, use one of the methods mentioned:\n \n ```sh\n $ i=4\n $ _=$(( i++ ))\n $ echo $i\n 5\n ```\n \n ### Exceptions:\n \n None.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Double quote to prevent globbing and word splitting. [SC2086]"},{"from": "gpt", "value": "## Double quote to prevent globbing and word splitting.\n \n ### Problematic code:\n \n ```sh\n echo $1\n for i in $*; do :; done # this one and the next one also apply to expanding arrays.\n for i in $@; do :; done\n ```\n \n ### Correct code:\n \n ```sh\n echo \"$1\"\n for i in \"$@\"; do :; done # or, 'for i; do'\n ```\n \n ### Rationale\n \n The first code looks like \"print the first argument\". It's actually \"Split the first argument by IFS (spaces, tabs and line feeds). Expand each of them as if it was a glob. Join all the resulting strings and filenames with spaces. Print the result.\"\n \n The second one looks like \"iterate through all arguments\". It's actually \"join all the arguments by the first character of IFS (space), split them by IFS and expand each of them as globs, and iterate on the resulting list\". The third one skips the joining part.\n \n Quoting variables prevents word splitting and glob expansion, and prevents the script from breaking when input contains spaces, line feeds, glob characters and such.\n \n Strictly speaking, only expansions themselves need to be quoted, but for stylistic reasons, entire arguments with multiple variable and literal parts are often quoted as one:\n \n ```sh\n $HOME/$dir/dist/bin/$file # Unquoted (bad)\n \"$HOME\"/\"$dir\"/dist/bin/\"$file\" # Minimal quoting (good)\n \"$HOME/$dir/dist/bin/$file\" # Canonical quoting (good)\n ```\n \n When quoting composite arguments, make sure to exclude globs and brace expansions, which lose their special meaning in double quotes: `\"$HOME/$dir/src/*.c\"` will not expand, but `\"$HOME/$dir/src\"/*.c` will.\n \n Note that `$( )` starts a new context, and variables in it have to be quoted independently:\n \n ```sh\n echo \"This $variable is quoted $(but this $variable is not)\"\n echo \"This $variable is quoted $(and now this \"$variable\" is too)\"\n ```\n \n ## Exceptions\n Sometimes you want to split on spaces, like when building a command line:\n \n ```sh\n options=\"-j 5 -B\"\n [[ $debug == \"yes\" ]] && options=\"$options -d\"\n make $options file\n ```\n \n Just quoting this doesn't work. Instead, you should have used an array (bash, ksh, zsh):\n \n ```sh\n options=(-j 5 -B) # ksh88: set -A options -- -j 5 -B\n [[ $debug == \"yes\" ]] && options=(\"${options[@]}\" -d)\n make \"${options[@]}\" file\n ```\n \n or a function (POSIX):\n \n ```sh\n make_with_flags() {\n [ \"$debug\" = \"yes\" ] && set -- -d \"$@\"\n make -j 5 -B \"$@\"\n }\n make_with_flags file\n ```\n \n 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=''`.\n \n Similarly, you might want an optional argument:\n \n ```sh\n debug=\"\"\n [[ $1 == \"--trace-commands\" ]] && debug=\"-x\"\n bash $debug script\n ```\n \n 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:\n \n ```sh\n debug=\"\"\n [[ $1 == \"--trace-commands\" ]] && debug=\"yes\"\n bash ${debug:+\"-x\"} script\n ```\n \n This is better than an unquoted value because the alternative value can be properly quoted, e.g. `wget ${output:+ -o \"$output\"}`.\n \n Here are two common cases where this warning seems unnecessary but may still be beneficial:\n \n ```sh\n cmd <<< $var # Requires quoting on Bash 3 (but not 4+)\n : ${var=default} # Should be quoted to avoid DoS when var='*/*/*/*/*/*'\n ```\n \n As always, this warning can be [ignored](https://www.shellcheck.net/wiki/ignore) on a case-by-case basis.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Quote `EOF` to make here document expansions happen on the server side rather than on the client. [SC2087]"},{"from": "gpt", "value": "## Quote `EOF` to make here document expansions happen on the server side rather than on the client.\n \n ### Problematic code:\n \n ```sh\n ssh host.example.com << EOF\n echo \"Logged in on $HOSTNAME\"\n EOF\n ```\n \n ### Correct code:\n \n ```sh\n ssh host.example.com << \"EOF\"\n echo \"Logged in on $HOSTNAME\"\n EOF\n ```\n \n ### Rationale:\n \n When the end token of a here document is unquoted, parameter expansion and command substitution will happen on in contents of the here doc.\n \n This means that before sending the commands to the server, the client replaces `$HOSTNAME` with localhost, thereby sending `echo \"Logged in on localhost\"` to the server. This has the effect of printing the client's hostname instead of the server's.\n \n Scripts with any kind of variable use are especially problematic because all references will be expanded before the script run. For example,\n \n ```sh\n ssh host << EOF\n x=\"$(uname -a)\"\n echo \"$x\"\n EOF\n ```\n \n will never print anything, neither client nor server details, since before evaluation, it will be expanded to:\n \n ```sh\n x=\"Linux localhost ... x86_64 GNU/Linux\"\n echo \"\"\n ```\n \n By quoting the here token, local expansion will not take place, so the server sees `echo \"Logged in on $HOSTNAME\"` which is expanded and printed with the server's hostname, which is usually the intention.\n \n ### Exceptions:\n \n If the client should expand some or all variables, this message can and should be ignored.\n \n To expand a mix of local and remote variables, the here doc end token should be unquoted, and the remote variables should be escaped, e.g.\n \n ```sh\n ssh host.example.com << EOF\n echo \"Logged in on \\$HOSTNAME from $HOSTNAME\"\n EOF\n ```\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Tilde does not expand in quotes. Use `$HOME`. [SC2088]"},{"from": "gpt", "value": "## Tilde does not expand in quotes. Use `$HOME`.\n \n ### Problematic code:\n \n ```sh\n rm \"~/Desktop/$filename\"\n ```\n \n ### Correct code:\n \n ```sh\n rm \"$HOME/Desktop/$filename\"\n ```\n \n ### Rationale:\n \n Tilde does not expand to the user's home directory when it's single or double quoted. Use double quotes and `$HOME` instead.\n \n Alternatively, the `~/` can be left unquoted, as in `rm ~/\"Desktop/$filename\"`.\n \n ### Exceptions\n \n If you don't want the tilde to be expanded, you can ignore this message.\n \n ### Related resources:\n \n * StackOverflow: [Why isn't tilde (~) expanding inside double quotes?](https://stackoverflow.com/questions/41871596/why-isnt-tilde-expanding-inside-double-quotes)\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Quotes/backslashes will be treated literally. Use an array. [SC2089]"},{"from": "gpt", "value": "# Quotes/backslashes will be treated literally. Use an array.\n \n ### Problematic code:\n \n ```sh\n args='-lh \"My File.txt\"'\n ls $args\n ```\n \n ### Correct code:\n \n In Bash/Ksh with arrays:\n \n ```sh\n args=(-lh \"My File.txt\")\n ls \"${args[@]}\"\n ```\n \n or in POSIX overwriting `\"$@\"`:\n \n ```sh\n set -- -lh \"My File.txt\"\n ls \"$@\"\n ```\n \n or in POSIX via functions:\n \n ```sh\n myls() { ls \"-lh\" \"My File.txt\"; }\n myls\n ```\n \n ### Rationale:\n \n Bash does not interpret data as code. Consider almost any other languages, such as Python:\n \n ```python\n print 1+1 # prints 2\n a=\"1+1\"\n print a # prints 1+1, not 2\n ```\n \n Here, `1+1` is Python syntax for adding numbers. However, passing a literal string containing this expression does not cause Python to interpret it, see the `+` and produce the calculated result.\n \n Similarly, `\"My File.txt\"` is Bash syntax for a single word with a space in it. However, passing a literal string containing this expression does not cause Bash to interpret it, see the quotes and produce the tokenized result.\n \n The solution is to use an array instead, whenever possible.\n \n If due to `sh` compatibility you can't use arrays, you can sometimes use functions instead. Instead of trying to create a set of arguments that has to be passed to a command, create a function that calls the function with arguments plus some more:\n \n ```sh\n ffmpeg_with_args() {\n ffmpeg -filter_complex '[#0x2ef] setpts=PTS+1/TB [sub] ; [#0x2d0] [sub] overlay' \"$@\"\n }\n ffmpeg_with_args -i \"My File.avi\" \"Output.avi\"\n ```\n \n In other cases, you may have to use `eval` instead, though this is often fragile and insecure. If you get it wrong, it'll appear to work great in all test cases, and may still lead to various forms of security vulnerabilities and breakage:\n \n ```sh\n quote() { local q=${1//\\'/\\'\\\\\\'\\'}; echo \"'$q'\"; }\n args=\"-lh $(quote \"My File.txt\")\"\n eval ls \"$args\" # Do not use unless you understand implications\n ```\n \n If you ever accidentally forget to use proper quotes, such as with:\n \n ```sh\n for f in *.txt; do\n args=\"-lh '$1'\" # Example security exploit\n eval ls \"$args\" # Do not copy and use\n done\n ```\n \n Then you can use `touch \"'; rm -rf \\$'\\x2F'; '.txt\"` (or someone can trick you into downloading a file with this name, or create a zip file or git repo containing it, or changing their nick and have your chat client create the file for a chat log, or...), and running the script to list your files will run the command `rm -rf /`.\n \n ### Exceptions\n \n Few and far between, such as, prompt variables. This from `man bash` \"PROMPTING\": \n \n > After the string is decoded, it is expanded via parameter expansion, command\n > substitution, arithmetic expansion, and quote removal, subject to the value of the promptvars shell\n > option (see the description of the shopt command under SHELL BUILTIN COMMANDS below). This can have\n > unwanted side effects if escaped portions of the string appear within command substitution or contain\n > characters special to word expansion.\n >\n \n ### Additional resources\n \n * [Wooledge BashFAQ #50](http://mywiki.wooledge.org/BashFAQ/050): I'm trying to put a command in a variable, but the complex cases always fail!\n * [StackOverflow: In bash, why do shell commands ignore quotes in arguments when the arguments are passed to them as a variable?](https://stackoverflow.com/questions/12136948/in-bash-why-do-shell-commands-ignore-quotes-in-arguments-when-the-arguments-are)\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Quotes/backslashes in this variable will not be respected. [SC2090]"},{"from": "gpt", "value": "# Quotes/backslashes in this variable will not be respected.\n \n See companion warning, [[SC2089]].\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Remove surrounding `$()` to avoid executing output (or use `eval` if intentional). [SC2091]"},{"from": "gpt", "value": "## Remove surrounding `$()` to avoid executing output (or use `eval` if intentional).\n \n ### Problematic code:\n \n ```sh\n if $(which epstopdf)\n then\n echo \"Found epstopdf\"\n fi\n ```\n \n or\n \n ```sh\n make_command() {\n printf 'cat header %q footer > %q\\n' \"$1\" \"$2\" | tee log\n }\n $(make_command foo.html output/foo.html)\n ```\n \n ### Correct code:\n \n ```sh\n if which epstopdf\n then\n echo \"Found epstopdf\"\n fi\n ```\n \n or \n \n ```sh\n make_command() {\n printf 'cat header %q footer > %q\\n' \"$1\" \"$2\" | tee log\n }\n eval \"$(make_command foo.html output/foo.html)\"\n ```\n ### Rationale:\n \n ShellCheck has detected that you have a command that just consists of a command substitution. This often happens when you want to run a command (possibly from a variable name), without realizing that `$(..)` is for capturing and not for executing.\n \n For example, if you have this shell function:\n \n sayhello() { echo \"hello world\"; }\n \n Then `$(sayhello)` will:\n \n 1. Run `sayhello`, capturing \"hello world\"\n 1. Run `hello world`, resulting in `bash: hello: command not found`\n \n Meanwhile, just `sayhello` will:\n \n 1. Run `sayhello`, outputting \"hello world\" to screen\n \n Note that this is equally true if the command is in a variable, e.g. `x=sayhello; $($x)`.\n \n If you *do* have a command that outputs a second command, similar to how `ssh-agent` outputs `export` commands to run, then you should do this via `eval`. This way, quotes, pipes, redirections, semicolons, and other shell constructs will work as expected. Note that this kind of design is best avoided when possible, since correctly escaping all values can be difficult and error prone. \n \n ### Exceptions:\n \n None.\n \n ### Related resources:\n \n * StackOverflow: [Bash Function -> Command not found](https://stackoverflow.com/questions/18611842/bash-function-command-not-found)\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Remove backticks to avoid executing output. [SC2092]"},{"from": "gpt", "value": "## Remove backticks to avoid executing output.\n \n Backticks does the same thing as `$(..)`. See [[SC2091]] for a description of the same problem with this syntax.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Remove `exec ` if script should continue after this command. [SC2093]"},{"from": "gpt", "value": "## Remove `exec ` if script should continue after this command.\n \n ### Problematic code:\n \n ```sh\n echo \"Starting compilation\"\n exec ./compile\n echo \"Starting deployment\"\n exec ./deploy\n ```\n \n ### Correct code:\n \n ```sh\n echo \"Starting compilation\"\n ./compile\n echo \"Starting deployment\"\n ./deploy\n ```\n \n ### Rationale:\n \n The script contains an `exec` command followed by other commands in the same block. This is likely an error because the script will not resume after an `exec` command.\n \n Instead, \"exec\" refers to the Unix process model's idea of execution (see [`execve(2)`](http://man7.org/linux/man-pages/man2/execve.2.html)), in which the current process stops its current program and replaces it with a new one. This is mainly used in wrapper scripts.\n \n To execute another script or program and then continue, simply drop the `exec` as in the example.\n \n ### Exceptions:\n \n If the code after the `exec` is only there to handle a failure in executing the command you can ignore this warning. For this reason, ShellCheck suppresses the warning if `exec` is only followed by `echo`/`exit` commands.\n \n ### Related resources:\n \n * StackOverflow: [My shell script stops after exec](https://stackoverflow.com/questions/3877657/my-shell-script-stops-after-exec)\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Make sure not to read and write the same file in the same pipeline. [SC2094]"},{"from": "gpt", "value": "## Make sure not to read and write the same file in the same pipeline.\n \n ### Problematic code:\n \n ```sh\n grep foo file.txt | sed -e 's/foo/bar/g' > file.txt\n ```\n \n ### Correct code:\n \n ```sh\n grep foo file.txt | sed -e 's/foo/bar/g' > tmpfile && mv tmpfile file.txt\n ```\n \n ### Rationale:\n \n Each step in a pipeline runs in parallel.\n \n In this case, `grep foo file.txt` will immediately try to read `file.txt` while `sed .. > file.txt` will immediately try to truncate it.\n \n This is a race condition, and results in the file being partially or (far more likely) entirely truncated.\n \n Note that this can also be a problem when you write to a file and read from it later in the pipe. The second command (which reads the file) may not see all the output of the first. An exception in this case is a non-greedy file reader like `less`, for example `python foo.py 2> errfile.txt | less - errfile.txt` will successfully allow you to see stdout and stderr separately in less.\n \n ### Exceptions\n \n You can ignore this error if:\n \n * The file is a device or named pipe. These files don't truncate in the same way.\n * The command mentions the filename but doesn't read/write it, such as `echo log.txt > log.txt`.\n \n ### Additional Resources\n \n * [StackOverflow: bash redirect input from file back into same file](https://stackoverflow.com/questions/6696842/bash-redirect-input-from-file-back-into-same-file)\n * [BashPitfalls: `cat file | sed s/foo/bar/ > file`](https://mywiki.wooledge.org/BashPitfalls#pf13)\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Use `ssh -n` to prevent ssh from swallowing stdin. [SC2095]"},{"from": "gpt", "value": "## Use `ssh -n` to prevent ssh from swallowing stdin.\n \n The same error applies to multiple commands, like `ffmpeg -nostdin` and `mplayer -noconsolecontrols`.\n \n ### Problematic code:\n \n ```sh\n while read -r host\n do\n ssh \"$host\" \"uptime\"\n done < hosts.txt\n ```\n \n ### Correct code:\n \n ```sh\n while read -r host\n do\n ssh -n \"$host\" \"uptime\"\n done < hosts.txt\n ```\n \n or\n \n ```sh\n while read -r host\n do\n ssh \"$host\" <<'EOF'\n uptime\n EOF\n done < hosts.txt\n ```\n or\n \n By using a pipe and avoiding the use of the stdin file descriptor, this ensures that commands in the loop are not interfered with.\n \n ```sh\n exec 3< hosts.txt\n while read -r host\n do\n ssh \"$host\" \"uptime\"\n done <&3\n # Close the file descriptor\n exec 3<&-\n ```\n \n ### Rationale:\n \n Commands that process stdin will compete with the `read` statement for input. This is especially tricky for commands you wouldn't expect reads from stdin, like `ssh .. uptime`, `ffmpeg` and `mplayer`.\n \n The most common symptom of this is a `while read` loop only running once, even though the input contains many lines. This is because the rest of the lines are swallowed by the offending command.\n \n To refuse such commands input, you can use a command specific option like `ssh -n` or `ffmpeg -nostdin`. \n \n More generally, you can also redirect their stdin with `< /dev/null`. This works for all commands with this behavior.\n \n ### Exceptions:\n \n None.\n \n ### Related resources:\n \n * [BashFaq: I'm reading a file line by line and running ssh or ffmpeg, only the first line gets processed!](https://mywiki.wooledge.org/BashFAQ/089)\n * [StackOverflow: Shell script while read line loop stops after the first line\n ](https://stackoverflow.com/questions/13800225/shell-script-while-read-line-loop-stops-after-the-first-line)\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: On most OS, shebangs can only specify a single parameter. [SC2096]"},{"from": "gpt", "value": "## On most OS, shebangs can only specify a single parameter.\n \n ### Problematic code:\n \n ```sh\n #!/usr/bin/env bash -x\n ```\n \n ### Correct code:\n \n ```sh\n #!/usr/bin/env bash\n set -x\n ```\n \n ### Rationale:\n \n Most operating systems, including POSIX, Linux and FreeBSD, allow only a single parameter in the shebang. The example is equivalent to calling `env 'bash -x'` instead of `env 'bash' '-x'`, and it will therefore fail.\n \n The shebang should be rewritten to use at most one parameter. Shell options can instead be set in the body of the script.\n \n ### Exceptions\n \n macOS X currently allows multiple words in the shebang. Scripts running on OSX exclusively can ignore this warning.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: This assignment is only seen by the forked process. [SC2097]"},{"from": "gpt", "value": "## This assignment is only seen by the forked process.\n \n ### Problematic code:\n \n ```sh\n name=World cmd -m \"Hello $name\"\n ```\n \n ### Correct code:\n \n ```sh\n name=World\n cmd -m \"Hello $name\"\n ```\n \n If the original goal was to limit the scope of the variable, this can also be done in a subshell:\n \n ```sh\n (\n name=World\n cmd -m \"Hello $name\"\n ) # 'name' does not leave this subshell\n ```\n \n ### Rationale:\n \n In `name=World cmd \"$name\"`, `name=World` is passed in as part of the environment to `cmd` (i.e., in the `envp` parameter to [execve(2)](http://linux.die.net/man/2/execve)). This means that `cmd` and its children will see the parameter, but no other processes will.\n \n However, `\"$name\"` is not expanded by `cmd`. `\"$name\"` is expanded by the shell before `cmd` is ever executed, and thus it will not use the new value.\n \n The solution is to set the variable first, then use it as a parameter. If limited scope is desired, a `( subshell )` can be used.\n \n ### Exceptions\n \n In the strange and fabricated scenarios where the script and a program uses a variable name for two different purposes, you can ignore this message. This is hard to conceive, since scripts should use lowercase variable names specifically to avoid collisions with the environment.\n \n ### Related resources:\n \n * [BashFaq: Why doesn't foo=bar echo \"$foo\" print bar?](https://mywiki.wooledge.org/BashFAQ/104)\n * [StackOverflow: Prefixing variable assignment doesn't work with echo](https://stackoverflow.com/questions/36380569/prefixing-variable-assignment-doesnt-work-with-echo?rq=1)\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: This expansion will not see the mentioned assignment. [SC2098]"},{"from": "gpt", "value": "## This expansion will not see the mentioned assignment.\n \n See companion warning [[SC2097]].\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Use `$((..))` for arithmetics, e.g. `i=$((i + 2))` [SC2099]"},{"from": "gpt", "value": "## Use `$((..))` for arithmetics, e.g. `i=$((i + 2))`\n \n ### Problematic code:\n \n ```sh\n i=3\n i=i + 2\n ```\n \n ### Correct code:\n \n ```sh\n i=3\n i=$((i + 2))\n ```\n \n ### Rationale:\n \n Unlike most languages, variable assignments in shell scripts are space sensitive and (almost) always assign strings.\n \n To evaluate a mathematical expressions, use `$((..))` as in the correct code:\n \n i=$((i + 2)) # Spaces are fine inside $((...))\n \n In the problematic code, `i=i + 2` will give an error `+: command not found` because the expression is interpreted similar to something like `LC_ALL=C wc -c` instead of numerical addition:\n \n Prefix assignment Command Argument\n LC_ALL=C wc -c\n i=i + 2\n \n ### Exceptions:\n \n If you wanted to assign a literal string, quote it:\n \n game_score=\"0 - 2\"\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Use `$((..))` for arithmetics, e.g. `i=$((i + 2))` [SC2100]"},{"from": "gpt", "value": "## Use `$((..))` for arithmetics, e.g. `i=$((i + 2))`\n \n ### Problematic code:\n \n ```sh\n i=3\n i=i+2\n ```\n \n ### Correct code:\n \n ```sh\n i=3\n i=$((i + 2))\n ```\n \n ### Rationale:\n \n Unlike most languages, variable assignments (almost) always assigns strings and not expressions. In the example code, `i` will become the string `i+2` instead of the intended `5`. \n \n To instead evaluate a mathematical expressions, use `$((..))` as in the correct code.\n \n ### Exceptions:\n \n If you wanted to assign a literal string, quote it:\n \n description=\"friendly-looking\"\n \n ShellCheck (as of v0.5) doesn't recognize Bash/Ksh numeric variables created with `declare -i` where this syntax is valid. Using `$((..))` still works, but you can also [[ignore]] this warning.\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Named class needs outer `[]`, e.g. `[[:digit:]]`. [SC2101]"},{"from": "gpt", "value": "## Named class needs outer `[]`, e.g. `[[:digit:]]`.\n \n ### Problematic code:\n \n ```sh\n gzip file[:digit:]*.txt\n ```\n \n ### Correct code:\n \n ```sh\n gzip file[[:digit:]]*.txt\n ```\n \n ### Rationale:\n \n Predefined character groups are supposed to be used inside character ranges. `[:digit:]` matches one of \"digt:\" just like `[abc]` matches one of \"abc\". `[[:digit:]]` matches a digit.\n \n ### Exceptions\n \n When passing an argument to `tr` which parses these by itself without relying on globbing, you should quote it instead, e.g. `tr -d '[:digit:]'`\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Ranges can only match single chars (mentioned due to duplicates). [SC2102]"},{"from": "gpt", "value": "## Ranges can only match single chars (mentioned due to duplicates).\n \n ### Problematic code:\n \n ```sh\n echo [100-999].txt\n ```\n \n ### Correct code:\n \n ```sh\n echo [1-9][0-9][0-9].txt\n ```\n ### Rationale:\n \n ShellCheck found a glob range expression (such as `[a-z]`) that contains multiple of the same character.\n \n Range expressions can only be used to match a single character in a given set, so `[ab]` and `[abba]` will both match the same thing: either one `a` or one `b`. \n \n Having multiple of the same character often means you're trying to match more than one character, such as in the problematic example where someone tried to match any number from 100 to 999. Instead, it matches a single digit just like `[0-9].txt`, and specifies 0, 1 and 9 multiple times.\n \n In Bash, most uses can be rewritten using [extglob](https://mywiki.wooledge.org/glob#extglob) and/or [brace expansion](https://mywiki.wooledge.org/BraceExpansion). For example:\n \n ```sh\n cat *.[dev,prod,test].conf # Doesn't work\n cat *.{dev,prod,test}.conf # Works in bash\n cat *.@(dev|prod|test).conf # Works in bash with `shopt -s extglob`\n ```\n \n In POSIX sh, you may have to write multiple globs, one after the other:\n \n ```sh\n cat *.dev.conf *.prod.conf *.test.conf\n ```\n \n ### Exceptions:\n \n There is currently a bug in which a range expression whose contents is a variable gets parsed verbatim, e.g. `[$foo]`. In this case, either ignore the warning or make the square brackets part of the variable contents instead.\n \n v0.7.2 and below would unintentionally show this warning for subscripts in arrays in `[[ -v array[xx] ]]` and other dereferencing operators. In these versions, you can either [[ignore]] the message or quote the word (as in `[[ -v 'array[xx]' ]]`)\n \n Note that IPv6 URLs trigger this warning, but the correct solution in this case is to quote them:\n \n curl 'http://[2607:f8b0:4002:c0c::65]/'\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Use a `( subshell )` to avoid having to `cd` back. [SC2103]"},{"from": "gpt", "value": "## Use a `( subshell )` to avoid having to `cd` back.\n \n ### Problematic code:\n \n ```sh\n for dir in */\n do\n cd \"$dir\"\n convert index.png index.jpg\n cd ..\n done\n ```\n \n \n ### Correct code:\n \n ```sh\n for dir in */\n do\n (\n cd \"$dir\" || exit\n convert index.png index.jpg\n )\n done\n ```\n \n or\n \n ```sh\n for dir in */\n do\n cd \"$dir\" || exit\n convert index.png index.jpg\n cd ..\n done\n ```\n \n ### Rationale:\n \n When doing `cd dir; somestuff; cd ..`, `cd dir` can fail when permissions are lacking, if the dir was deleted, or if `dir` is actually a file.\n \n In this case, `somestuff` will run in the wrong directory and `cd ..` will take you to an even more wrong directory. In a loop, this will likely cause the next `cd` to fail as well, propagating this error and running these commands far away from the intended directories.\n \n Check `cd`s exit status and/or use subshells to limit the effects of `cd`.\n \n ### Exceptions\n \n If you set variables you can't use a subshell. In that case, you should definitely check the exit status of `cd`, which will also silence this suggestion.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: In functions, use `return` instead of `break`. [SC2104]"},{"from": "gpt", "value": "## In functions, use `return` instead of `break`.\n \n ### Problematic code:\n \n ```sh\n foo() {\n if [[ -z $1 ]]\n then\n break\n fi\n echo \"Hello $1\"\n }\n ```\n \n ### Correct code:\n \n ```sh\n foo() {\n if [[ -z $1 ]]\n then\n return 1\n fi\n echo \"Hello $1\"\n }\n ```\n ### Rationale:\n \n `break` or `continue` are used to abort or continue a loop, and are not the right way to exit a function. Use `return` instead.\n \n ### Exceptions:\n \n The `break` or `continue` may be intended for a loop that calls the function:\n \n ```\n # Rarely valid\n foo() { break; echo $?; }\n while true; do foo; done\n ```\n \n This is undefined behavior in POSIX sh. Different shells do different things.\n \n When the function is called from a loop:\n \n * `ksh` keeps going and `$?` is 0.\n * `bash` version 4.4+ prints an error \"break: only meaningful in a \\`for', \\`while', or \\`until' loop\", the function keeps going, and `$?` is 0. \n * `bash` versions before 4.4, will return from the function, break the loop calling the function, or exit a subshell if there's one in between.\n * `dash`, BusyBox `ash`: like above.\n \n When the function is not called from a loop:\n \n * All `bash` versions print an error \"break: only meaningful in a \\`for', \\`while', or \\`until' loop\", the function keeps going, and `$?` is 0. \n * `ksh`, `dash` and `ash` silently keep going and `$?` is 0.\n \n Due to the many different implementations, many of which are not helpful, it's recommended to use proper flow control. A typical solution is making sure the function `return`s success/failure, and calling `myfunction || break` in the loop.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: `break` is only valid in loops [SC2105]"},{"from": "gpt", "value": "## `break` is only valid in loops\n \n ### Problematic code:\n \n ```sh\n case \"$1\" in\n -v)\n verbose=1\n break\n ;;\n -d)\n debug=1\n esac\n ```\n \n ### Correct code:\n \n ```sh\n case \"$1\" in\n -v)\n verbose=1\n ;;\n -d)\n debug=1\n esac\n ```\n ### Rationale:\n \n `break` or `continue` was found outside a loop. These statements are valid only in loops. In particular, `break` is not required in `case` statements as there is no implicit fall-through.\n \n To return from a function or sourced script, use `return`. To exit a script, use `exit`.\n \n ### Exceptions:\n \n It's possible to `break`/`continue` in a function without a loop. The call will then affect the loop – if any – that the function is invoked from, but this is obviously not good coding practice.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: This only exits the subshell caused by the pipeline. [SC2106]"},{"from": "gpt", "value": "## This only exits the subshell caused by the pipeline.\n \n ### Problematic code:\n \n ```sh\n for i in a b c; do\n echo hi | grep -q bye | break\n done\n ```\n \n ### Correct code:\n \n ```sh\n for i in a b c; do\n echo hi | grep -q bye || break\n done\n ```\n ### Rationale:\n \n The most common cause of this issue is probably using a single `|` when `||` was intended. The reason this message appears, though, is that a construction like this, intended to surface a failure inside of a loop:\n \n ```sh\n for i in a b c; do false | break; done; echo ${PIPESTATUS[@]}\n ```\n \n may appear to work:\n ```\n $ for i in a b c; do false | break; done; echo ${PIPESTATUS[@]}\n 1 0\n ```\n \n What's actually happening, though, becomes clear if we add some `echo`s; the entire loop completes, and the `break` has no effect.\n \n ```sh\n $ for i in a b c; do echo $i; false | break; done; echo ${PIPESTATUS[@]}\n a\n b\n c\n 1 0\n $ for i in a b c; do false | break; echo $i; done; echo ${PIPESTATUS[@]}\n a\n b\n c\n 0\n ```\n \n Because bash processes pipelines by creating subshells, control statements like `break` only take effect in the subshell.\n \n ### Related resources:\n \n * Contrast with the related, but different, problem in [this link](https://unix.stackexchange.com/questions/166546/bash-cannot-break-out-of-piped-while-read-loop-process-substitution-works).\n * [Bash Reference Manual: Pipelines](https://www.gnu.org/software/bash/manual/bash.html#Pipelines), esp.:\n > Each command in a pipeline is executed in its own subshell.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Instead of `[ a && b ]`, use `[ a ] && [ b ]`. [SC2107]"},{"from": "gpt", "value": "## Instead of `[ a && b ]`, use `[ a ] && [ b ]`.\n \n ### Problematic code:\n \n ```sh\n [ \"$1\" = \"-v\" && -z \"$2\" ]\n ```\n \n ### Correct code:\n \n ```sh\n [ \"$1\" = \"-v\" ] && [ -z \"$2\" ]\n ```\n \n ### Rationale:\n \n `&&` can not be used in a `[ .. ]` test expression. Instead, make two `[ .. ]` expressions and put the `&&` between them.\n \n ### Exceptions:\n \n None.\n \n ### Related resources:\n \n * [Bash Pitfalls: [ \"$foo\" = bar && \"$bar\" = foo ]](https://mywiki.wooledge.org/BashPitfalls#pf6)\n * [StackOverflow: using and (&&) operator in if statement bash script\n ](https://stackoverflow.com/questions/16396146/using-and-operator-in-if-statement-bash-script/16396181)\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: In `[[..]]`, use `&&` instead of `-a`. [SC2108]"},{"from": "gpt", "value": "## In `[[..]]`, use `&&` instead of `-a`.\n \n ### Problematic code:\n \n ```sh\n [[ \"$1\" = \"-v\" -a -z \"$2\" ]]\n ```\n \n ### Correct code:\n \n ```sh\n [[ \"$1\" = \"-v\" && -z \"$2\" ]]\n ```\n \n ### Rationale:\n \n `-a` for logical AND is not supported in a `[[ .. ]]` expression. Use `&&` instead.\n \n ### Exceptions:\n \n None.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Instead of `[ a || b ]`, use `[ a ] || [ b ]`. [SC2109]"},{"from": "gpt", "value": "## Instead of `[ a || b ]`, use `[ a ] || [ b ]`.\n \n ### Problematic code:\n \n ```sh\n [ \"$1\" = \"-v\" || \"$1\" = \"-help\" ]\n ```\n \n ### Correct code:\n \n ```sh\n [ \"$1\" = \"-v\" ] || [ \"$1\" = \"-help\" ]\n ```\n \n ### Rationale:\n \n `||` cannot be used in a `[ .. ]` test expression. Instead, make two `[ .. ]` expressions and put the `||` between them.\n \n ### Exceptions:\n \n None.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: In `[[..]]`, use `||` instead of `-o`. [SC2110]"},{"from": "gpt", "value": "## In `[[..]]`, use `||` instead of `-o`.\n \n ### Problematic code:\n \n ```sh\n [[ \"$1\" = \"-v\" -o \"$1\" = \"-help\" ]]\n ```\n \n ### Correct code:\n \n ```sh\n [[ \"$1\" = \"-v\" || \"$1\" = \"-help\" ]]\n ```\n \n ### Rationale:\n \n `-o` for logical OR is not supported in a `[[ .. ]]` expression. Use `||` instead.\n \n ### Exceptions:\n \n None.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: ksh does not allow `function` keyword and `()` at the same time. [SC2111]"},{"from": "gpt", "value": "## ksh does not allow `function` keyword and `()` at the same time.\n \n ### Problematic code:\n \n ```sh\n #!/bin/ksh\n function foo() {\n echo \"Hello World\"\n }\n ```\n \n ### Correct code:\n \n ```sh\n # POSIX sh function\n foo() {\n echo \"Hello World\"\n }\n ```\n \n or\n \n ```sh\n # ksh extended function\n function foo {\n echo \"Hello World\"\n }\n ```\n \n ### Rationale:\n \n Ksh allows two ways of defining functions: POSIX sh style `foo() { ..; }` and Ksh specific `function foo { ..; }`.\n \n ShellCheck found a function definition that uses both at the same time, `function foo() { ..; }` which is not allowed. Use one or the other.\n \n Note that the two are not identical, for example:\n \n * Using `typeset` in a `function foo` will create a local variable, while in `foo()` it will create a global variable.\n * `function foo` has its own trap context, while `foo()` shares them with the current process.\n * `function foo` will set `$0` to foo, while `foo()` will inherit `$0` from the current process.\n \n ### Exceptions:\n \n In Bash, `function foo() { ..; }` is allowed, and `function foo` and `foo()` are identical. This warning does not trigger when the shebang is e.g. `#!/bin/bash`. \n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: `function` keyword is non-standard. Delete it. [SC2112]"},{"from": "gpt", "value": "## `function` keyword is non-standard. Delete it.\n \n ### Problematic code:\n \n ```sh\n #!/bin/sh\n function hello() {\n echo \"Hello World\"\n }\n ```\n \n ### Correct code:\n \n ```sh\n #!/bin/sh\n hello() {\n echo \"Hello World\"\n }\n ```\n \n The `function` keyword is a feature of Bash and Ksh, so code that uses it may be intended to be a Bash or Ksh script instead:\n \n ```sh\n #!/bin/bash\n function hello() {\n echo \"Hello World\"\n }\n ```\n \n ### Rationale:\n \n `function` is a non-standard keyword that can be used to declare functions in Bash and Ksh.\n \n In POSIX `sh` and `dash`, a function is instead declared without the `function` keyword as in the correct example. \n \n ### Exceptions:\n \n None.\n \n ### Related resources:\n \n * [Function Definition Command](https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_09_05) in the POSIX spec\n * [Shell Functions](https://www.gnu.org/software/bash/manual/html_node/Shell-Functions.html) in the Bash manual\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: `function` keyword is non-standard. Use `foo()` instead of `function foo`. [SC2113]"},{"from": "gpt", "value": "## `function` keyword is non-standard. Use `foo()` instead of `function foo`.\n \n ### Problematic code:\n \n ```sh\n #!/bin/sh\n function hello {\n echo \"Hello World\"\n }\n ```\n \n ### Correct code:\n \n ```sh\n #!/bin/sh\n hello() {\n echo \"Hello World\"\n }\n ```\n \n ### Rationale:\n \n `function` is a non-standard keyword that can be used to declare functions in Bash and Ksh.\n \n In POSIX `sh` and `dash`, a function is defined without a `function` keyword. Instead, the function name is followed by `()` as in the correct example.\n \n ### Exceptions:\n \n None\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Warning: deletes a system directory. [SC2114]"},{"from": "gpt", "value": "## Warning: deletes a system directory.\n \n ### Problematic code:\n \n ```sh\n rm -rf /usr /lib/nvidia-current/xorg/xorg\n ```\n \n ### Correct code:\n \n ```sh\n rm -rf /usr/lib/nvidia-current/xorg/xorg\n ```\n \n ### Rationale:\n \n The example line of code was an actual bug in the [Bumblebee NVIDIA driver](https://github.com/MrMEEE/bumblebee-Old-and-abbandoned/commit/a047be85247755cdbe0acce6f1dafc8beb84f2ac).\n \n Due to an accidental space, it deleted `/usr` instead of just the particular directory.\n \n ### Exceptions:\n \n If you do intend to delete a system directory, such as when working in a chroot or initramfs, you can disable this message with a directive: \n \n ```sh\n # shellcheck disable=SC2114\n rm -rf /usr \n ```\n \n Previous versions of shellcheck, up to and including 0.4.6, would ignore `rm` statements containing a `--` (an arbitrary convention). This is no longer the case.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Use `\"${var:?}\"` to ensure this never expands to `/*` . [SC2115]"},{"from": "gpt", "value": "## Use `\"${var:?}\"` to ensure this never expands to `/*` .\n \n ### Problematic code:\n \n ```sh\n rm -rf \"$STEAMROOT/\"*\n ```\n \n ### Correct code:\n \n ```sh\n rm -rf \"${STEAMROOT:?}/\"*\n ```\n \n ### Rationale:\n \n If `STEAMROOT` is empty, this will [end up deleting everything](https://github.com/ValveSoftware/steam-for-linux/issues/3671) in the system's root directory.\n \n Using `:?` will cause the command to fail if the variable is null or unset. Similarly, you can use `:-` to set a default value if applicable.\n \n In the case command substitution, assign to a variable first and then use `:?`. This is relevant even if the command seems simple and obviously correct, since forks and execs can fail due to external system limits and conditions, resulting in a blank substitution.\n \n For more details about `:?` see the \"Parameter Expansion\" section of the Bash man page.\n \n ### Exceptions:\n \n None.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Useless echo? Instead of `cmd $(echo foo)`, just use `cmd foo`. [SC2116]"},{"from": "gpt", "value": "## Useless echo? Instead of `cmd $(echo foo)`, just use `cmd foo`.\n \n ### Problematic code:\n \n ```sh\n greeting=$(echo \"Hello, $name\")\n # or\n tar czf \"$(echo \"$(date +%F).tar.gz\")\" *\n ```\n \n ### Correct code:\n \n ```sh\n greeting=\"Hello, $name\"\n # or\n tar czf \"$(date +%F).tar.gz\" *\n ```\n \n ### Rationale:\n \n You appear to be using `echo` to write a value to stdout, and then using `$(..)` or `` `..` `` to capture the value again. This is as pointless as mailing yourself a postcard: you already have what you want, so there's no need to send it on a round trip.\n \n You can just replace `$(echo myvalue)` with `myvalue`.\n \n ### Exceptions\n \n Sometimes this pattern is used because of side effect of `echo` or expansions. For example, here `$(echo ..)` is used to expand a glob.\n ```\n glob=\"*.png\"\n files=\"$(echo $var)\"\n ```\n \n The `echo` is not useless, but this code is problematic because it concatenates filenames by spaces. This will break filenames containing spaces and other characters later when the list is split again. Better options are:\n \n * Arrays, if supported by the shell: `files=( $glob ); echo \"The first file is ${files[0]}\"`\n * Positional parameters when possible: `set -- $glob; echo \"The first file is $1\"`\n * Delaying expansion until it's needed: `for file in $glob; do ...`\n \n All three methods will let you avoid issues with special characters in filenames.\n \n As another example, here `$(echo ..)` is used to expand escape sequences:\n ```\n unexpanded='var\\tvalue'\n expanded=\"$(echo \"$var\")\"\n ```\n \n In this case, use `printf` instead. It's well defined with regard to escape sequences. \n \n Finally, if you really do want to concatenate a series of elements by a character like space, consider doing it explicitly with `for` or `printf` (e.g. `printf '%s\\n' $glob`).\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: To run commands as another user, use `su -c` or `sudo`. [SC2117]"},{"from": "gpt", "value": "## To run commands as another user, use `su -c` or `sudo`.\n \n ### Problematic code:\n \n ```sh\n whoami\n su\n whoami\n ```\n \n ### Correct code:\n \n ```sh\n whoami\n sudo whoami\n ```\n \n ### Rationale:\n \n It's commonly believed that `su` makes a session run as another user. In reality, it starts an entirely new shell, independent of the one currently running your script.\n \n `su; whoami` will start a root shell and wait for it to exit before running `whoami`. It will not start a root shell and then proceed to run `whoami` in it.\n \n To run commands as another user, use `sudo some command` or `su -c 'some command'`. `sudo` is preferred when available, as it doesn't require additional quoting and can be configured to run passwordless if desired.\n \n \n ### Exceptions\n \n If you're aware of the above and want to e.g. start an interactive shell for a user, feel free to ignore this message.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Ksh does not support `|&`. Use `2>&1 |` [SC2118]"},{"from": "gpt", "value": "## Ksh does not support `|&`. Use `2>&1 |`\n \n ### Problematic code:\n \n ```sh\n #!/usr/bin/ksh\n make |& tee ~/log\n ```\n \n ### Correct code:\n \n ```sh\n #!/usr/bin/ksh\n make 2>&1 | tee ~/log\n ```\n ### Rationale:\n \n You are using the Bash specific shorthand `|&`, but your script is running with Ksh. Rewrite it to its full, POSIX-compatible form as shown in the example.\n \n ### Exceptions:\n \n None\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Use `foo \"$@\"` if function's `$1` should mean script's `$1`. [SC2119]"},{"from": "gpt", "value": "## Use `foo \"$@\"` if function's `$1` should mean script's `$1`.\n \n See companion warning [[SC2120]].\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: foo references arguments, but none are ever passed. [SC2120]"},{"from": "gpt", "value": "# foo references arguments, but none are ever passed.\n \n ### Problematic code:\n \n ```sh\n sayhello() {\n echo \"Hello $1\"\n }\n sayhello\n ```\n \n `./myscript World` just prints \"Hello \" instead of \"Hello World\".\n \n ### Correct code:\n \n ```sh\n sayhello() {\n echo \"Hello $1\"\n }\n sayhello \"$@\"\n ```\n \n `./myscript World` now prints \"Hello World\".\n \n ### Rationale:\n \n In a function, `$1` and up refers to the function's parameters, not the script's parameters.\n \n If you want to process your script's parameters in a function, you have to explicitly pass them. You can do this with `myfunction \"$@\"`.\n \n Note that `\"$@\"` refers to the current context's positional parameters, so if you call a function from a function, you have to pass in `\"$@\"` to both of them:\n \n ```sh\n first() { second \"$@\"; }\n second() { echo \"The first script parameter is: $1\"; }\n first \"$@\"\n ```\n \n ### Exceptions\n \n If the parameters are optional and you currently just don't want to use them, you can ignore this message. In versions strictly greater than v0.6.0, ignoring SC2120 on a function will also disable SC2119 on each of the call sites.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: To assign a variable, use just `var=value`, not `set ..`. [SC2121]"},{"from": "gpt", "value": "## To assign a variable, use just `var=value`, not `set ..`.\n \n ### Problematic code:\n \n ```sh\n set var=42\n set var 42\n ```\n \n ### Correct code:\n \n ```sh\n var=42\n ```\n \n ### Rationale:\n \n `set` is not used to set or assign variables in Bourne shells. It's used to set shell options and positional parameters.\n \n To assign variables, use `var=value` with no `set` or other qualifiers.\n \n ### Exceptions\n \n If you actually do want to set positional parameters, simply quoting them or using `--` will make shellcheck stop warning, e.g. `set -- var1 var2` or `set \"foo=bar\"`.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: `>=` is not a valid operator. Use `! a < b` instead. [SC2122]"},{"from": "gpt", "value": "## `>=` is not a valid operator. Use `! a < b` instead.\n \n ### Problematic code:\n \n ```sh\n [[ a <= b ]]\n ```\n \n ### Correct code:\n \n ```sh\n [[ ! a > b ]]\n ```\n \n ### Rationale:\n \n The operators `<=` and `>=` are not supported by Bourne shells. Instead of \"less than or equal\", rewrite as \"not greater than\".\n \n ### Exceptions\n \n None\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: `PATH` is the shell search path. Use another name. [SC2123]"},{"from": "gpt", "value": "## `PATH` is the shell search path. Use another name.\n \n ### Problematic code:\n \n ```sh\n PATH=/my/dir\n cat \"$PATH/myfile\"\n ```\n \n ### Correct code:\n \n Good practice: always use lowercase for unexported variables.\n \n ```sh\n path=/my/dir\n cat \"$path/myfile\"\n ```\n \n Bad practice: use another uppercase name.\n \n ```sh\n MYPATH=/my/dir\n cat \"$MYPATH/myfile\"\n ```\n \n ### Rationale:\n \n `PATH` is where the shell looks for the commands it executes. By inadvertently overwriting it, the shell will be unable to find commands (like `cat` in this case).\n \n You get this warning when ShellCheck suspects that you didn't meant to overwrite it (because it's a single path with no path separators).\n \n Best shell scripting practice is to always use lowercase variable names to avoid accidentally overwriting exported and internal variables.\n \n ### Exceptions\n \n If you're aware of the above and really do want to set your shell search path to `/my/dir`, you can ignore this warning.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Assigning an array to a string! Assign as array, or use `*` instead of `@` to concatenate. [SC2124]"},{"from": "gpt", "value": "## Assigning an array to a string! Assign as array, or use `*` instead of `@` to concatenate.\n \n ### Problematic code:\n \n ```sh\n # Want to store multiple elements in var\n var=$@\n for i in $var; do ..; done\n ```\n \n or\n \n ```sh\n set -- Hello World\n # Want to concatenate multiple elements into a single string\n msg=$@\n echo \"You said $msg\"\n ```\n \n ### Correct code:\n \n ```sh\n # Bash: use an array variable\n var=( \"$@\" )\n for i in \"${var[@]}\"; do ..; done\n \n # POSIX sh: without array support, one possible workaround\n # is to store elements concatenated with a delimiter (here linefeed/newline)\n var=$(printf '%s\\n' \"$@\")\n printf '%s\\n' \"$var\" | while IFS='' read -r line; do ..; done\n ```\n \n or\n \n ```sh\n #!/bin/sh\n set -- Hello World\n # Explicitly concatenates all the array elements into a single string\n msg=$*\n echo \"You said $msg\"\n ```\n \n ### Rationale:\n \n Arrays and `$@` can contain multiple elements. Simple variables contain only one. When assigning multiple elements to one element, the default behavior depends on the shell (bash concatenates with spaces, zsh concatenates with first char of `IFS`).\n \n Since doing this usually indicates a bug, ShellCheck warns and asks you to be explicit about what you want.\n \n If you want to assign N elements as N elements in Bash or Ksh, use an array, e.g. `myArray=( \"$@\" )`.\n \n Dash and POSIX sh do not support arrays. In this case, either concatenate the values with some delimiter that you can split on later (the example uses linefeeds and splits them back up with a `while read` loop), or keep the values as positional parameters without putting them in an intermediate variable. \n \n If you want to assign N elements as 1 element by concatenating them, use `*` instead of `@`, e.g. `myVar=${myArray[*]}` (this separates elements with the first character of `IFS`, usually space).\n \n The same is true for `${@: -1}`, which results in 0 or 1 elements: `var=${*: -1}` assigns the last element or an empty string.\n \n ### Exceptions\n \n None.\n \n ### Adding an element to an array may trigger this warning when you forget the parenthesis.\n ```\n filelist=\"${filelist[@]}\" \"$filename\"\n ```\n What was meant is:\n ```\n filelist=(\"${filelist[@]}\" \"$filename\")\n ```\n Note: This syntax is compatible with older shells;\n in later shells (bash 3.1+ and zsh 4.2+), you can do `filelist+=(\"$filename\")`.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Brace expansions and globs are literal in assignments. Quote it or use an array. [SC2125]"},{"from": "gpt", "value": "## Brace expansions and globs are literal in assignments. Quote it or use an array.\n \n ### Problematic code:\n \n ```sh\n foo={1..9}\n echo \"$foo\"\n ```\n ```sh\n foo=\"/some/path/*\"\n echo \"$foo\"\n ```\n \n ### Correct code:\n \n ```sh\n foo=( {1..9} )\n echo \"${foo[@]}\"\n ```\n ```sh\n foo=(/some/path/*)\n echo \"${foo[@]}\"\n ```\n \n Note that either of these will trigger [[SC3030]] (\"In POSIX sh, array references are undefined\") if you are using `sh` and not e.g. `bash`.\n \n ### Rationale:\n \n `echo *.png {1..9}` expands to all png files and numbers from 1 to 9, but `var=*.png` or `var={1..9}` will just assign the literal strings `'*.png'` and `'{1..9}'`.\n \n To make the variable contain all png files or 1 through 9, use an array as demonstrated.\n \n If you intended to assign these values as literals, quote them (e.g. `var=\"*.png\"`).\n \n ### Exceptions\n \n None.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Consider using `grep -c` instead of `grep | wc` [SC2126]"},{"from": "gpt", "value": "## Consider using `grep -c` instead of `grep | wc`\n \n ### Problematic code:\n \n ```sh\n grep foo | wc -l\n ```\n \n ### Correct code:\n \n ```sh\n grep -c foo\n ```\n \n #### For multiple files\n \n Instead of:\n \n ```sh\n grep foo *.log | wc -l\n ```\n \n You can pipe all the file contents into `grep` (passing the files directly to `grep` causes `-c` to print each file's count separately, rather than the total):\n \n ```sh\n cat *.log | grep foo -c\n ```\n \n ### Rationale:\n \n This is purely a stylistic issue. `grep` can count lines without piping to `wc`.\n \n Often this number is only used to see whether there are matches (i.e. `== 0`). In these cases it's clearer and more efficient to use `grep -q` and check its exit status:\n \n ```sh\n if grep -q pattern file; then\n echo \"The file contains the pattern\"\n fi\n ```\n \n Also note that in `foo | grep bar | wc -l`, `wc` will mask the exit code of `grep` by default (i.e. without `set -o pipefail`), and always return success. If replacing with `foo | grep -c bar`, `grep` will exit non-zero when there are no matches. This is generally desirable (see above), but may require handling when used with `set -e`.\n \n ### Exceptions\n \n If you find piping to `wc` is clearer in a given situation it's fine to [[ignore]] this error.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: To use `${ ..; }`, specify `#!/usr/bin/env ksh`. [SC2127]"},{"from": "gpt", "value": "## To use `${ ..; }`, specify `#!/usr/bin/env ksh`.\n \n (Or \"To use cases with `;;&`, specify `#!/usr/bin/env bash`)\n \n ### Problematic code:\n \n ```sh\n #!/usr/bin/env bash\n var=${ mycmd; };\n ```\n \n or\n \n ```\n #!/usr/bin/env ksh\n case \"$1\" in\n foo) echo \"Foo!\" ;;&\n f*) echo \"F-something at least\" ;;\n esac\n ```\n \n ### Correct code:\n \n ```sh\n #!/usr/bin/env ksh\n var=${ mycmd; };\n ```\n \n or\n \n ```\n #!/usr/bin/env bash\n case \"$1\" in\n foo) echo \"Foo!\" ;;&\n f*) echo \"F-something at least\" ;;\n esac\n ```\n \n ### Rationale:\n \n You are using a shell syntax feature not supported by the script's shell. Either rewrite the construct, or switch to a different shell interpreter.\n \n ### Exceptions:\n \n None\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Expanding an array without an index only gives the element in the index 0. [SC2128]"},{"from": "gpt", "value": "## Expanding an array without an index only gives the element in the index 0.\n \n ### Problematic code:\n \n ```sh\n myarray=(foo bar)\n for f in $myarray\n do\n cat \"$f\"\n done\n ```\n \n ### Correct code:\n \n ```sh\n myarray=(foo bar)\n for f in \"${myarray[@]}\"\n do\n cat \"$f\"\n done\n ```\n \n ### Rationale:\n \n When referencing arrays, `$myarray` is equivalent to `${myarray[0]}` -- which is usually the first of multiple elements. This is also true for associative arrays. Therefore, if 0 (zero) is not a valid key, `$myarray` expands to an empty string.\n \n To get all elements as separate parameters, use the index `@` (and make sure to double quote). In the example, `echo \"${myarray[@]}\"` is equivalent to `echo \"foo\" \"bar\"`.\n \n To get all elements as a single parameter, concatenated by the first character in `IFS`, use the index `*`. In the example, `echo \"${myarray[*]}\"` is equivalent to `echo \"foo bar\"`.\n \n ### Bugs:\n \n There is a [known issue](https://github.com/koalaman/shellcheck/issues/1309) with this check's handling of `local` variables, causing ShellCheck to flag variables that were previously declared as arrays, even if they are in different scopes.\n \n The easiest workaround is to simply use different variable names. Alternatively, you can [[ignore]] the check.\n \n It is also possible to satisfy ShellCheck by declaring the `local` variable separately from assigning to it, e.g.:\n \n ```sh\n foo () {\n local -a baz\n baz+=(\"foo\" \"bar\")\n echo \"${baz[@]}\"\n }\n \n bar () {\n local baz # ShellCheck gets confused if these lines are merged as local baz=\"qux\"\n baz=\"qux\"\n echo \"$baz\"\n }\n ```\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Consider using `{ cmd1; cmd2; } >> file` instead of individual redirects. [SC2129]"},{"from": "gpt", "value": "## Consider using `{ cmd1; cmd2; } >> file` instead of individual redirects.\n \n ### Problematic code:\n \n ```sh\n echo foo >> file\n date >> file\n cat stuff >> file\n \n ```\n \n ### Correct code:\n \n ```sh\n {\n echo foo\n date\n cat stuff\n } >> file\n ```\n \n ### Rationale:\n \n Rather than adding `>> something` after every single line, you can simply group the relevant commands and redirect the group. So the file has to be opened and closed only once and it means a performance gain.\n \n ### Exceptions:\n \n This is mainly a stylistic issue, and can freely be ignored.\n \n Note: shell traps which would ordinarily emit output to stdout or stderr on catching their condition will have output swallowed into the redirect when the trap is triggered from within the grouping.\n \n ### Related resources:\n \n * [BashFaq: How can I redirect the output of multiple commands at once?](https://mywiki.wooledge.org/BashFAQ/014)\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: `-eq` is for integer comparisons. Use `=` instead. [SC2130]"},{"from": "gpt", "value": "## `-eq` is for integer comparisons. Use `=` instead.\n \n _Note: This warning seems replace by SC2170 or SC2309. Removed in [V0.4.2 - 2016-01-10](https://github.com/koalaman/shellcheck/commit/b9cb040128f0f90ad43efbdae7ae2a8d36941cfe)_\n \n ### Problematic code:\n \n ```sh\n [[ $foo -eq \"Y\" ]]\n ```\n \n ### Correct code:\n \n ```sh\n [[ $foo = \"Y\" ]]\n ```\n \n ### Rationale:\n \n Shells have two sets of comparison operators: for integers (`-eq`, `-gt`, ...) and strings (`=`, `>`, ...). ShellCheck has noticed that you're using an integer comparison with string data.\n \n If you are in fact comparing integers, double check your parameters. Certain mistakes like `$$foo` or `${bar}}` can introduce non-numeric characters into otherwise numeric arguments.\n \n ### Exceptions\n \n None.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: This expands when defined, not when used. Consider escaping. [SC2139]"},{"from": "gpt", "value": "## This expands when defined, not when used. Consider escaping.\n \n ### Problematic code:\n \n ```sh\n alias whereami=\"echo $PWD\"\n ```\n \n ### Correct code:\n \n ```sh\n alias whereami='echo $PWD'\n ```\n \n ### Rationale:\n \n With double quotes, this particular alias will be defined as `echo /home/me`, so it will always print the same path. This is rarely intended.\n \n By using single quotes or escaping any expansions, we define the alias as `echo $PWD`, which will be expanded when we use the alias. This is the far more common use case.\n \n Note that even if you expect that the variable will never change, it may still be better to quote it. This prevents a second round of evaluation later:\n \n default=\"Can't handle failure, aborting\"\n trap \"echo $default; exit 1\" err\n false \n \n The trap now has a syntax error, because instead of running `echo $default`, it runs `echo Can't handle ..` which has an unmatched single quote. Avoid early expansion unless you're equally comfortable putting `eval` in there.\n \n ### Exceptions\n \n If you don't mind that your alias definition is expanded at define time (and its result expanded again at evaluation time), you can ignore this warning.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Word is of the form `\"A\"B\"C\"` (B indicated). Did you mean `\"ABC\"` or `\"A\\\"B\\\"C\"`? [SC2140]"},{"from": "gpt", "value": "## Word is of the form `\"A\"B\"C\"` (B indicated). Did you mean `\"ABC\"` or `\"A\\\"B\\\"C\"`?\n \n ### Problematic code:\n \n ```sh\n echo \"\" > file.html\n ```\n \n or\n \n ```sh\n export \"var\"=\"42\"\n ```\n \n ### Correct code:\n \n ```sh\n echo \"\" > file.html\n ```\n \n or\n \n ```sh\n export \"var=42\"\n ```\n \n \n ### Rationale:\n \n This warning triggers when an unquoted literal string is found suspiciously sandwiched between two double quoted strings.\n \n This usually indicates one of:\n \n - quotes that were supposed to be nested, and therefore need to be escaped (like the `` example)\n - quotes that are just plain unnecessary (like the `export` example).\n \n Without escaping, the inner two quotes of the sandwich (the end quote of the first section and the start quote of the second section) are no-ops. The following two statements are identical, so the quotes that were intended to be part of the html output are instead removed:\n \n ```sh\n echo \"\" > file.html\n echo \"\" > file.html\n ```\n \n Similarly, these statements are identical, but work as intended:\n \n ```sh\n export \"var\"=\"42\"\n export \"var=42\"\n ```\n \n ### Exceptions\n \n If you know that the quotes are ineffectual but you prefer it stylistically, you can ignore this message.\n \n It's common not to realize that double quotes can span multiple elements, or to stylistically prefer to quote individual variables. For example, these statements are identical, but the first is laboriously and redundantly quoted:\n \n ```sh\n http://\"$user\":\"$password\"@\"$host\"/\"$path\"\n \"http://$user:$password@$host/$path\"\n ```\n \n When ShellCheck detects the first style (i.e. the double quotes include only a single element each), it will suppress the warning.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Did you mean `IFS=$'\\t'` ? [SC2141]"},{"from": "gpt", "value": "## Did you mean `IFS=$'\\t'` ?\n \n ### Problematic code:\n \n ```sh\n IFS=\"\\t\"\n ```\n \n ### Correct code:\n \n ```sh\n IFS=$'\\t'\n ```\n or POSIX:\n \n ```sh\n IFS=\"$(printf '\\t')\"\n ```\n \n \n ### Rationale:\n \n `IFS=\"\\t\"` splits on backslash and the letter \"t\". `IFS=$'\\t'` splits on tab.\n \n ### Exceptions\n \n It's extremely rare to want to split on the letter \"n\" or \"t\", rather than linefeed or tab.\n \n \n ### Related resources\n \n See https://github.com/koalaman/shellcheck/wiki/SC1012\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Aliases can't use positional parameters. Use a function. [SC2142]"},{"from": "gpt", "value": "## Aliases can't use positional parameters. Use a function.\n \n ### Problematic code:\n \n ```sh\n alias archive='mv \"$@\" /backup'\n ```\n \n ### Correct code:\n \n ```sh\n archive() { mv \"$@\" /backup; }\n \n ```\n \n ### Rationale:\n \n Aliases just substitute the start of a command with something else. They therefore can't use positional parameters, such as `$1`. Rewrite your alias as a function.\n \n ### Exceptions\n \n If your alias ends up quoting the value, e.g. `alias cut_first=\"awk '{print \\$1}'\"`, you can technically [[ignore]] this error. However, you should consider turning this alias into a more readable function instead: `cut_first() { awk '{print $1}' \"$@\"; }`\n \n You can also [[ignore]] this warning if you intentionally referenced the positional parameters of its relevant context, knowing that it won't refer to the parameters of the alias itself. For example, `alias whatisthis='echo \"This is $0 -$-\" #'` will show the shell name with flags, i.e. `This is dash -smi` or `This is bash -himBs`, and is correct usage because it does not intend for `$0` to reflect anything related to the `whatisthis` alias or its invocation.\n \n \n ### Related resources:\n \n * [BashFaq: How can I make an alias that takes an argument?](https://mywiki.wooledge.org/BashFAQ/080)\n * [StackOverflow: Make a Bash alias that takes a parameter?](https://stackoverflow.com/questions/7131670/make-a-bash-alias-that-takes-a-parameter)\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Use `grep -q` instead of comparing output with `[ -n .. ]`. [SC2143]"},{"from": "gpt", "value": "## Use `grep -q` instead of comparing output with `[ -n .. ]`.\n \n ### Problematic code:\n \n ```sh\n if [ -n \"$(find . | grep 'IMG[0-9]')\" ]\n then\n echo \"Images found\"\n fi\n ```\n \n ### Correct code:\n \n ```sh\n if find . | grep -q 'IMG[0-9]'\n then\n echo \"Images found\"\n fi\n ```\n \n ### Rationale:\n \n The problematic code has to iterate the entire directory and read all matching lines into memory before making a decision.\n \n The correct code is cleaner and stops at the first matching line, avoiding both iterating the rest of the directory and reading data into memory.\n \n ### Exceptions\n \n The `pipefail` bash option may interfere with this rewrite, since the `if` will now in effect be evaluating the statuses of all commands instead of just the last one. Be careful using them together.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: `-e` doesn't work with globs. Use a `for` loop. [SC2144]"},{"from": "gpt", "value": "## `-e` doesn't work with globs. Use a `for` loop.\n \n ### Problematic code:\n \n ```sh\n if [ -e dir/*.mp3 ]\n then\n echo \"There are mp3 files.\"\n fi\n ```\n \n ### Correct code:\n \n ```sh\n for file in dir/*.mp3\n do\n if [ -e \"$file\" ]\n then\n echo \"There are mp3 files\"\n break\n fi\n done\n ```\n \n ### Rationale:\n \n `[ -e file* ]` only works if there's 0 or 1 matches. If there are multiple, it becomes `[ -e file1 file2 ]`, and the test fails.\n \n `[[ -e file* ]]` doesn't work at all.\n \n Instead, use a for loop to expand the glob and check each result individually.\n \n If you are looking for the existence of a directory, do:\n \n ```sh\n for f in /path/to/your/files*; do\n \n ## Check if the glob gets expanded to existing files.\n ## If not, f here will be exactly the pattern above\n ## and the exists test will evaluate to false.\n [ -e \"$f\" ] && echo \"files do exist\" || echo \"files do not exist\"\n \n ## This is all we needed to know, so we can break after the first iteration\n break\n done\n ```\n \n \n \n ### Exceptions\n \n If you are sure there will only ever be exactly 0 or 1 matches -- and `nullglob` is not enabled -- then the test happens to work.\n \n You may still want to consider making this assumption explicit and failing fast if it's ever violated:\n \n ```\n files=( dir/file* )\n [ \"${#files[@]}\" -ge 2 ] && exit 1\n if [ -e \"${files[0]}\" ]\n then \n echo \"The file exists\"\n else\n echo \"No such file\"\n fi\n ```\n \n ### Related resources:\n \n * [BashFaq: How can I check whether a directory is empty or not? How do I check for any *.mpg files, or count how many there are?](https://mywiki.wooledge.org/BashFAQ/004)\n * [sh - Check if a file exists with wildcard in shell script - Stack Overflow](https://stackoverflow.com/a/6364244/2309247)\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Argument mixes string and array. Use `*` or separate argument. [SC2145]"},{"from": "gpt", "value": "## Argument mixes string and array. Use `*` or separate argument.\n \n ### Problematic code:\n \n ```sh\n printf \"Error: %s\\n\" \"Bad parameters: $@\"\n ```\n \n ### Correct code:\n \n ```sh\n printf \"Error: %s\\n\" \"Bad parameters: $*\"\n ```\n \n ### Problematic code 2:\n \n ```sh\n printf \"Error: %s\\n\" \"Bad parameters: ${ARRAY_VAR[@]}\"\n ```\n \n ### Correct code 2:\n \n ```sh\n printf \"Error: %s\\n\" \"Bad parameters: \" \"${ARRAY_VAR[@]}\"\n ```\n \n ### Rationale:\n \n The behavior when concatenating a string and array is rarely intended. The preceding string is prefixed to the first array element, while the succeeding string is appended to the last one. The middle array elements are unaffected.\n \n E.g., with the parameters `foo`,`bar`,`baz`, `\"--flag=$@\"` is equivalent to the three arguments `\"--flag=foo\" \"bar\" \"baz\"`.\n \n If the intention is to concatenate all the array elements into one argument, use `$*`. This concatenates based on `IFS`.\n \n If the intention is to provide each array element as a separate argument, put the array expansion in its own argument.\n \n ### Exceptions\n \n The POSIX specified behavior of `$@` (and by extension arrays) as part of other strings is often unexpected:\n \n > if the parameter being expanded was embedded within a word, the first field shall be joined with the beginning part of the original word and the last field shall be joined with the end part of the original word. In all other contexts the results of the expansion are unspecified. If there are no positional parameters, the expansion of '@' shall generate zero fields, even when '@' is within double-quotes; however, if the expansion is embedded within a word which contains one or more other parts that expand to a quoted null string, these null string(s) shall still produce an empty field, except that if the other parts are all within the same double-quotes as the '@', it is unspecified whether the result is zero fields or one empty field.\n \n If you're aware of this and intend to take advantage of it, you can ignore this warning. However, you can also usually also rewrite it into a less surprising form. For example, here's a wrapper script that uses this behavior to substitute certain commands by defining a function for them:\n \n #!/bin/sh\n fixed_fgrep() { grep -F \"$@\"; }\n fixed_echo() { printf '%s\\n' \"$*\"; }\n fixed_seq() { echo \"seq is not portable\" >&2; return 1; }\n \n if command -v \"fixed_$1\" > /dev/null 2>&1\n then\n # shellcheck disable=SC2145 # I know how fixed_\"$@\" behaves and it's correct!\n fixed_\"$@\"\n else\n \"$@\"\n fi\n \n Here's the same script without relying on this behavior:\n \n #!/bin/sh\n fixed_fgrep() { grep -F \"$@\"; }\n fixed_echo() { printf '%s\\n' \"$*\"; }\n fixed_seq() { echo \"seq is not portable\" >&2; return 1; }\n \n cmd=\"$1\"\n shift\n \n if command -v \"fixed_$cmd\" > /dev/null 2>&1\n then\n # Perhaps more straight forward with fewer surprises:\n \"fixed_$cmd\" \"$@\"\n else\n \"$cmd\" \"$@\"\n fi\n \n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: This action ignores everything before the `-o`. Use `\\( \\)` to group. [SC2146]"},{"from": "gpt", "value": "## This action ignores everything before the `-o`. Use `\\( \\)` to group.\n \n ### Problematic code:\n \n ```sh\n find . -name '*.avi' -o -name '*.mkv' -exec cp {} /media \\;\n ```\n \n ### Correct code:\n \n ```sh\n find . \\( -name '*.avi' -o -name '*.mkv' \\) -exec cp {} /media \\;\n ```\n Note that the space between `\\(` and `-name` in this command is significant.\n \n ### Rationale:\n \n In `find`, two predicates with no operator between them is considered a logical, short-circuiting AND (as if using `-a`). E.g., `-name '*.mkv' -exec ..` is the same as `-name '*.mkv' -a -exec ..`.\n \n `-a` has higher precedence than `-o`, so `-name '*.avi' -o -name '*.mkv' -a -exec ..` is equivalent to `-name '*.avi' -o \\( -name '*.mkv' -a -exec .. \\)`.\n \n In other words, the problematic code means \"if name matches `*.avi`, do nothing. Otherwise, if it matches `*.mkv`, execute a command.\".\n \n In the correct code, we use `\\( \\)` to group to get the evaluation order we want. The correct code means \"if name matches `*.avi` or `*.mkv`, then execute a command\", which was what was intended.\n \n ### Exceptions\n \n If you're aware of this, you can either ignore this error or group to make it explicit. For example, to decompress all gz files except tar.gz, you can use:\n \n ```sh\n find . -name '*.tar.gz' -o \\( -name '*.gz' -exec gzip -d {} + \\)\n ```\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Literal tilde in PATH works poorly across programs. [SC2147]"},{"from": "gpt", "value": "## Literal tilde in PATH works poorly across programs.\n \n ### Problematic code:\n \n ```sh\n PATH=\"$PATH:~/bin\"\n ```\n \n ### Correct code:\n \n ```sh\n PATH=\"$PATH:$HOME/bin\"\n ```\n \n ### Rationale:\n \n Having literal `~` in PATH is a bad idea. Bash handles it, but nothing else does.\n \n This means that even if you're always using Bash, you should avoid it because any invoked program that relies on PATH will effectively ignore those entries.\n \n For example, `make` may say `foo: Command not found` even though `foo` works fine from the shell and Make and Bash both use the same PATH. You'll get similar messages from any non-bash scripts invoked, and `whereis` will come up empty.\n \n Use `$HOME` or full path instead.\n \n ### Exceptions\n \n If your directory name actually contains a literal tilde, you can ignore this message.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Tips depend on target shell and yours is unknown. Add a shebang. [SC2148]"},{"from": "gpt", "value": "## Tips depend on target shell and yours is unknown. Add a shebang.\n \n ### Problematic code:\n \n ```sh\n echo \"$RANDOM\" # Does this work?\n ```\n \n ### Correct code:\n \n ```sh\n #!/bin/sh\n echo \"$RANDOM\" # Unsupported in sh. Produces warning.\n ```\n \n or\n \n ```sh\n #!/bin/bash\n echo \"$RANDOM\" # Supported in bash. No warnings.\n ```\n \n ### Rationale:\n \n Different shells support different features. To give effective advice, ShellCheck needs to know which shell your script is going to run on. You will get a different numbers of warnings about different things depending on your target shell.\n \n If you add a shebang (e.g. `#!/bin/bash` as the first line), the OS will use this interpreter when the script is executed, and ShellCheck will use this shell when offering advice.\n \n If you for any reason can't or won't add a shebang, there are multiple other ways to let shellcheck know which shell you're coding for:\n \n * Specify the shell using the `-s` or `--shell` flag, e.g. `shellcheck -s bash myfile`\n * Use a shellcheck [[directive]], adding `# shellcheck shell=ksh` before the first command in the file.\n * Give the script a `.bash`, `.ksh` or `.dash` extension (`.sh` will not assume `--shell=sh` since it's so generic)\n \n ### Exceptions\n \n None. Please either add a shebang, directive, extension or use `-s` to maximize ShellCheck's usefulness. \n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Remove `$`/`${}` for numeric index, or escape it for string. [SC2149]"},{"from": "gpt", "value": "## Remove `$`/`${}` for numeric index, or escape it for string.\n \n _Note: Removed in [v0.5.0 - 2018-06-01](https://github.com/koalaman/shellcheck/commit/d16bf41c3d0785732394e5d9ff0830525cf5ea79)_\n \n ### Problematic code:\n \n ```sh\n # Regular array\n index=42\n echo $((array[$index]))\n ```\n \n or\n \n ```sh\n # Associative array\n index=banana\n echo $((array[$index]))\n ```\n \n ### Correct code:\n \n ```\n # Regular array\n index=42\n echo $((array[index]))\n ```\n \n or\n \n ```sh\n # Associative array\n index=banana\n echo $((array[\\$index]))\n ```\n \n ### Rationale:\n \n For a numerically indexed array, the `$` is mostly pointless and can be removed like in [[SC2004]].\n \n For associative arrays, the `$` should be escaped to avoid accidental dereferencing:\n \n ```sh\n declare -A array\n index='$1'\n array[$index]=42\n echo \"$(( array[$index] ))\" # bash: array: bad array subscript\n echo \"$(( array[\\$index] ))\" # 42\n ```\n \n ### Exceptions\n \n None.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: `-exec` does not automatically invoke a shell. Use `-exec sh -c ..` for that. [SC2150]"},{"from": "gpt", "value": "## `-exec` does not automatically invoke a shell. Use `-exec sh -c ..` for that.\n \n ### Problematic code:\n \n ```sh\n find . -type f -exec 'cat {} | wc -l' \\;\n ```\n \n ### Correct code:\n \n ```sh\n find . -type f -exec sh -c 'cat {} | wc -l' \\; # Insecure\n find . -type f -exec sh -c 'cat \"$1\" | wc -l' _ {} \\; # Secure\n ```\n \n Sometimes the command can also be rewritten to not require `find` to invoke a shell:\n \n ```sh\n find . -type f -exec wc -l {} \\; | cut -d ' ' -f 1\n ```\n \n ### Rationale:\n \n find `-exec` and `-execdir` uses `execve(2)` style semantics, meaning it expects an executable and zero or more arguments that should be passed to it.\n \n It does not use `system(3)` style semantics, meaning it does not accept a shell command as a string, to be parsed and evaluated by the system's command interpreter.\n \n If you want `find` to execute a shell command, you have to specify `sh` (or `bash`) as the executable, `-c` as first argument and your shell command as the second.\n \n To prevent command injection, the filename can be passed as a separate argument to sh and referenced as a positional parameter.\n \n ### Exceptions\n \n This warning would trigger falsely if executing a program with spaces in the path, if no other arguments were specified.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Only one integer 0-255 can be returned. Use stdout for other data. [SC2151]"},{"from": "gpt", "value": "## Only one integer 0-255 can be returned. Use stdout for other data.\n \n ### Problematic code:\n \n ```sh\n myfunc() {\n return foo bar\n }\n ```\n \n ### Correct code:\n \n ```sh\n myfunc() {\n echo foo\n echo bar\n return 0\n }\n ```\n \n ### Rationale:\n \n In bash, `return` can only be used to signal success or failure (0 = success, 1-255 = failure).\n \n To return textual or multiple values from a function, write them to stdout and capture them with command substitution instead.\n \n See [[SC2152]] for more information.\n \n ### Exceptions:\n \n None\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Can only return 0-255. Other data should be written to stdout. [SC2152]"},{"from": "gpt", "value": "## Can only return 0-255. Other data should be written to stdout.\n \n ### Problematic code:\n \n ```sh\n myfunc() {\n return \"Hello $USER\"\n }\n ```\n \n ### Correct code:\n \n ```sh\n myfunc() {\n echo \"Hello $USER\"\n return 0\n }\n ```\n \n ### Rationale:\n \n In many languages, `return` is used to return from the function with a final result.\n \n In sh/bash, `return` can only be used to signal success or failure (0 = success, 1-255 = failure), more akin to `throw/raise` in other languages.\n \n Results should instead be written to stdout and captured:\n \n ```sh\n message=$(myfunc)\n echo \"The function wrote: $message\"\n ```\n \n In functions that return small integers, such as getting the cpu temperature, the value should still be written to stdout. `return` should be reserved for error conditions, such as \"can't determine CPU temperature\". Error or failure messages should be written to stderr.\n \n Note in particular that `return -1` is equivalent to `return 255`, but that `return 1` is the more canonical way of expressing the first possible error code.\n \n ### Exceptions:\n \n None\n \n ### Related resources:\n \n * [BashFaq: How do I return a string (or large number, or negative number) from a function?](https://mywiki.wooledge.org/BashFAQ/084) \"return\" only lets me give a number from 0 to 255.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Possible Misspelling: MYVARIABLE may not be assigned. Did you mean MY_VARIABLE? [SC2153]"},{"from": "gpt", "value": "## Possible Misspelling: MYVARIABLE may not be assigned. Did you mean MY_VARIABLE?\n \n ### Problematic code:\n \n ```sh\n MY_VARIABLE=\"hello world\"\n echo \"$MYVARIABLE\"\n ```\n \n ### Correct code:\n \n ```sh\n MY_VARIABLE=\"hello world\"\n echo \"$MY_VARIABLE\"\n ```\n \n ### Rationale:\n \n ShellCheck has noticed that you reference a variable that is not assigned in the script, but which has a name similar to another known variable. You should verify that the variable name is spelled correctly.\n \n Note: This error only triggers for environment variables (all uppercase variables), and only when they have names similar to another known variable in the script. If the variable is script-local, it should by convention have a lowercase name, and will in that case be caught by [[SC2154]] whether or not it resembles another name.\n \n ### Exceptions:\n \n If you've double checked and ensured that you did not intend to reference the specified variable, you can disable this message with a [[directive]]. The message will also not appear for guarded references like `${ENVVAR:-default}` or `${ENVVAR:?Unset error message here}`.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: var is referenced but not assigned. [SC2154]"},{"from": "gpt", "value": "## var is referenced but not assigned.\n \n ### Problematic code:\n \n ```sh\n var=name\n n=42\n echo \"$var_$n.jpg\" # overextended\n ```\n \n or\n \n ```sh\n target=\"world\"\n echo \"hello $tagret\" # misspelled\n ```\n \n or\n \n ```sh\n echo \"Result: ${mycmd -a myfile}\" # trying to execute commands\n ```\n \n ### Correct code:\n \n ```sh\n var=name\n n=42\n echo \"${var}_${n}.jpg\"\n ```\n \n or\n \n ```sh\n target=\"world\"\n echo \"hello $target\"\n ```\n \n or\n \n ```sh\n echo \"Result: $(mycmd -a myfile)\"\n ```\n \n ### Rationale:\n \n ShellCheck has noticed that you reference a variable that is not assigned. Double check that the variable is indeed assigned, and that the name is not misspelled.\n \n Note: This message only triggers for variables with lowercase characters in their name (`foo` and `kFOO` but not `FOO`) due to the standard convention of using lowercase variable names for unexported, local variables.\n \n ### Exceptions:\n \n ShellCheck intentionally does not attempt to figure out runtime or dynamic assignments like with `source \"$(date +%F).sh\"` or `eval var=value`. See [[SC2034]] for an extended discussion of why this is the case.\n \n If you know for a fact that the variable is set, you can use `${var:?}` to fail if the variable is unset (or empty), initialize it to a default value if uninitialized with `: \"${var:=}\"`, or explicitly initialize/declare it with `var=\"\"` or `declare var`. You can also disable the message with a [[directive]].\n \n ---\n \n ## Read more:\n \n POSIX - Parameter expansion:\n * https://stackoverflow.com/a/16753536/2309247\n * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_02\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Declare and assign separately to avoid masking return values. [SC2155]"},{"from": "gpt", "value": "## Declare and assign separately to avoid masking return values.\n \n ### Problematic code in the case of `export`:\n \n ```sh\n export foo=\"$(mycmd)\"\n ```\n \n #### Correct code:\n \n ```sh\n foo=\"$(mycmd)\"\n export foo\n ```\n \n #### Rationale:\n \n In the original code, the return value of `mycmd` is ignored, and `export` will instead always return true. This may prevent conditionals, `set -e` and traps from working correctly.\n \n When first marked for export and assigned separately, the return value of the assignment will be that of `mycmd`. This avoids the problem.\n \n Note that ShellCheck does not warn about masking of local read-only variables, such as `local -r foo=$(cmd)`, even though this also masks the return value. This is because the alternative `local foo; foo=$(cmd); local -r foo` is repetitive and cumbersome. To see warnings for this and many other additional cases of suppressed exit codes, enable `check-extra-masked-returns`.\n \n #### Exceptions:\n \n If you intend to ignore the return value of an assignment, you can either [[ignore]] this warning or use\n \n ```sh\n foo=$(mycmd) || true\n export foo\n ```\n \n Shellcheck does not warn about `export foo=bar` because `bar` is a literal and not a command substitution with an independent return value. \n \n ### Problematic code in the case of `local`:\n \n ```sh\n local foo=\"$(mycmd)\"\n ```\n \n #### Correct code:\n \n ```sh\n local foo\n foo=$(mycmd)\n ```\n \n #### Rationale\n \n The exit status of the command is overridden by the exit status of the creation of the local variable. For example:\n \n ```bash\n $ f() { local foo=$(false) && echo \"error was hidden\"; }; f\n error was hidden\n $ f() { local foo; foo=$(false) && echo \"error was hidden\"; }; f\n ```\n \n ### Problematic code in the case of `readonly`:\n \n ```sh\n readonly foo=\"$(mycmd)\"\n ```\n \n #### Correct code:\n \n ```sh\n foo=\"$(mycmd)\"\n readonly foo\n ```\n \n ## Word splitting and quoting issue with dash, maybe others\n \n A serious quoting problem with dash is another reason to declare and assign separately. Dash is the [default, `/bin/sh` shell on Ubuntu](https://wiki.ubuntu.com/DashAsBinSh). More specifically, dash version 0.5.8-2.10 and others cannot run these two examples:\n ```sh\n f(){ local e=$1; }\n f \"1 2\"\n \n export g=$(printf '%s' \"foo 2\")\n ``` \n While this runs fine in other shells, [dash doesn't treat any of these as assignments](http://mywiki.wooledge.org/BashPitfalls#local_var.3D.24.28cmd.29) and fails both like this:\n ```\n local: 2: bad variable name\n export: 2: bad variable name\n ```\n The direct workaround to this bug is to quote the right-hand-side of the assignment. Separating declaraction and assignment also makes this runs fine in any shell.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Injecting filenames is fragile and insecure. Use parameters. [SC2156]"},{"from": "gpt", "value": "## Injecting filenames is fragile and insecure. Use parameters.\n \n ### Problematic code:\n \n ```sh\n find . -name '*.mp3' -exec sh -c 'i=\"{}\"; sox \"$i\" \"${i%.mp3}.wav\"' \\;\n ```\n \n ### Correct code:\n \n ```sh\n find . -name '*.mp3' -exec sh -c 'i=\"$1\"; sox \"$i\" \"${i%.mp3}.wav\"' shell {} \\;\n ```\n \n ### Rationale:\n \n In the problematic example, the filename is passed by injecting it into a shell string. Any shell metacharacters in the filename will be interpreted as part of the script, and not as part of the filename. This can break the script and allow arbitrary code execution exploits.\n \n In the correct example, the filename is passed as a parameter. It will be safely treated as literal text. Note that when using the shell command with `-c`, the first parameter to the shell command (in the example \"shell\") becomes `$0` in the shell command's environment, where it is used e.g. in shell error messages (you can set it to an arbitrary value, but it makes sense to set it to the shell's name). You should not use the first parameter to the shell command as a data processing parameter because you cannot, for example, access `$0` via `$*` in the shell command (because `$*` starts with `$1`), and as previously mentioned, `$0` is used in the shell command's error messages, which would be confusing.\n \n ### Exceptions:\n \n None.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Argument to implicit `-n` is always true due to literal strings. [SC2157]"},{"from": "gpt", "value": "## Argument to implicit `-n` is always true due to literal strings.\n (Or: Argument to -z is always false due to literal strings. )\n \n ### Problematic code:\n \n ```sh\n if [ \"$foo \" ]\n then\n echo \"this is always true because of the trailing space\"\n fi\n ```\n \n ### Correct code:\n \n ```sh\n if [ \"$foo\" ]\n then\n echo \"correctly checks value\"\n fi\n ```\n \n ### Rationale:\n \n Since `[ str ]` and `[ -n str ]` check that the string is non-empty, any literal characters in the string -- including a space character like in the example -- will cause the test to always be true.\n \n Equivalently, since `[ -z str ]` checks that the string is empty, any literal character in the string will cause the test to always be false.\n \n Double check the string: you may have added trailing characters, or bad quotes or syntax. Some examples include:\n \n * `[ \"$foo \" ]` like in the example, where the space becomes part of the string\n * `[ \"{$foo}\" ]` instead of `[ \"${foo}\" ]`, where the `{` becomes part of the string\n * `[ \"$foo -gt 0\" ]` instead of `[ \"$foo\" -gt \"0\" ]`, where the `-gt` becomes part of the string\n \n \n ### Exceptions:\n \n None.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: `[ false ]` is true. Remove the brackets [SC2158]"},{"from": "gpt", "value": "## `[ false ]` is true. Remove the brackets\n \n ### Problematic code:\n \n ```sh\n if [ false ]\n then\n echo \"triggers anyways\"\n fi\n ```\n \n ### Correct code:\n \n ```sh\n if false\n then\n echo \"never triggers\"\n fi\n ```\n \n ### Rationale:\n \n `[ str ]` checks whether `str` is non-empty. It doesn't matter if `str` is `false`, it will still be evaluated for non-emptyness.\n \n Instead, use the command `false` which -- as the manual puts it -- does nothing, unsuccessfully.\n \n ### Exceptions:\n \n None\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: `[ 0 ]` is true. Use `false` instead. [SC2159]"},{"from": "gpt", "value": "## `[ 0 ]` is true. Use `false` instead.\n \n ### Problematic code:\n \n ```sh\n if [ 0 ]\n then\n echo \"always triggers\"\n fi\n ```\n \n ### Correct code:\n \n ```sh\n if false\n then\n echo \"never triggers\"\n fi\n ```\n \n ### Rationale:\n \n `[ str ]` checks whether `str` is non-empty. It doesn't matter if `str` is `0`, it will still be evaluated for non-emptyness.\n \n Instead, use the command `false` which -- as the manual puts it -- does nothing, unsuccessfully.\n \n ### Exceptions:\n \n None\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Instead of `[ true ]`, just use `true`. [SC2160]"},{"from": "gpt", "value": "## Instead of `[ true ]`, just use `true`.\n \n ### Problematic code:\n \n ```sh\n if [ true ]\n then\n echo \"always triggers\"\n fi\n ```\n \n ### Correct code:\n \n ```sh\n if true\n then\n echo \"always triggers\"\n fi\n ```\n \n ### Rationale:\n \n This is a stylistic suggestion to use `true` instead of `[ true ]`.\n \n `[ true ]` seems to suggest that the value \"true\" is somehow relevant to the statement. This is not the case, it doesn't matter. You can replace it with `[ false ]` or `[ wombat ]`, and it will still always be true:\n \n String | In brackets | Outside brackets\n --------|--------------|-----------------\n true | true | true\n false | true | false\n wombat | true | unknown command\n \n It's therefore better to use it without brackets, so that the \"true\" actually matters.\n \n ### Exceptions:\n \n None.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Instead of `[ 1 ]`, use `true`. [SC2161]"},{"from": "gpt", "value": "## Instead of `[ 1 ]`, use `true`.\n \n ### Problematic code:\n \n ```sh\n while [ 1 ]\n do\n echo \"infinite loop\"\n done\n ```\n \n ### Correct code:\n \n ```sh\n while true\n do\n echo \"infinite loop\"\n done\n ```\n \n ### Rationale:\n \n This is a stylistic suggestion to use `true` instead of `[ 1 ]`.\n \n `[ 1 ]` seems to suggest that the value \"1\" is somehow relevant to the statement. This is not the case: it doesn't matter. You can replace it with `[ 0 ]` or `[ wombat ]`, and it will still always be true.\n \n If you instead use `true`, the value is actually considered and can be inverted by replacing with `false`.\n \n On bash, you can also use `(( 1 ))`, which evaluates to true much like in C. `(( 0 ))` is similarly false.\n \n ### Exceptions:\n \n None.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: `read` without `-r` will mangle backslashes. [SC2162]"},{"from": "gpt", "value": "## `read` without `-r` will mangle backslashes.\n \n ### Problematic code:\n \n ```sh\n echo \"Enter name:\"\n read name\n ```\n \n ### Correct code:\n \n ```sh\n echo \"Enter name:\"\n read -r name\n ```\n \n or\n \n ```sh\n echo \"Enter name:\"\n IFS= read -r name\n ```\n \n ### Rationale:\n \n By default, `read` will interpret backslashes before spaces and line feeds (i.e. you can use backslashes in your string as an escape character). This is rarely expected or desired.\n \n Normally you just want to read data _including backslashes_ which are part of the input string and have no special escape meaning, which is what `read -r` does. You should always use `-r` unless you have a good reason not to:\n \n > -r\n >\n > If this option is given, backslash does not act as an escape character.\n \n #### Trimming whitespace\n \n Even with `read -r`, leading and trailing whitespace will be stripped from the input. Although this may sometimes be desirable or harmless it is often surprising and difficult to catch. Clearing the `IFS` disables this behavior, so `IFS= read -r` is generally safest.\n \n ### See Also\n \n * [Bash FAQ 001](https://mywiki.wooledge.org/BashFAQ/001)\n \n ### Exceptions:\n \n If you want backslashes to affect field splitting and line terminators instead of being read, you can disable this message with a [[directive]].\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: This does not export `FOO`. Remove `$`/`${}` for that, or use `${var?}` to quiet. [SC2163]"},{"from": "gpt", "value": "## This does not export `FOO`. Remove `$`/`${}` for that, or use `${var?}` to quiet.\n \n ### Problematic code:\n \n ```sh\n MYVAR=foo\n export $MYVAR\n ```\n \n ### Correct code:\n \n ```sh\n MYVAR=foo\n export MYVAR\n ```\n \n ### Rationale:\n \n `export` takes a variable name, but shellcheck has noticed that you give it an expanded variable instead. The problematic code does not export `MYVAR` but a variable called `foo` if any.\n \n ### Exceptions:\n \n If this is intentional and you do want to export `foo` instead of `MYVAR`, you can either use a directive:\n \n ```sh\n # shellcheck disable=SC2163\n export \"$MYVAR\"\n ```\n \n Or after (but not including) version 0.4.7, take advantage of the fact that ShellCheck only warns when no parameter expansion modifiers are applied:\n \n ```sh\n export \"${MYVAR}\" # ShellCheck warns\n export \"${MYVAR?}\" # No warning\n ```\n \n `${MYVAR?}` fails when `MYVAR` is unset, which is fine since `export` would have failed too. The main side effect is an improved runtime error message in that case.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Use `cd ... || exit` in case `cd` fails. [SC2164]"},{"from": "gpt", "value": "## Use `cd ... || exit` in case `cd` fails.\n \n ### Problematic code:\n \n ```sh\n cd generated_files\n rm -r *.c\n ```\n ```sh\n func(){\n cd foo\n do_something\n }\n ```\n \n ### Correct code:\n \n ```sh\n cd generated_files || exit\n rm -r *.c\n ```\n ```sh\n # For functions, you may want to use return:\n func(){\n cd foo || return\n do_something\n }\n ```\n \n ### Rationale:\n \n `cd` can fail for a variety of reasons: misspelled paths, missing directories, missing permissions, broken symlinks and more.\n \n If/when it does, the script will keep going and do all its operations in the wrong directory. This can be messy, especially if the operations involve creating or deleting a lot of files.\n \n To avoid this, make sure you handle the cases when `cd` fails. Ways to do this include\n \n * `cd foo || exit` as suggested to abort immediately, using exit code from failed `cd` command\n * `cd foo || { echo \"Failure\"; exit 1; }` abort with custom message\n * `cd foo || ! echo \"Failure\"` omitting \"abort with custom message\"\n * `if cd foo; then echo \"Ok\"; else echo \"Fail\"; fi` for custom handling\n * `<(cd foo && cmd)` as an alternative to `<(cd foo || exit; cmd)` in `<(..)`, `$(..)` or `( )`\n \n ### Exceptions:\n \n ShellCheck does not give this warning when `cd` is on the left of a `||` or `&&`, or the condition of a `if`, `while` or `until` loop. Having a `set -e` command anywhere in the script will disable this message, even though it won't necessarily prevent the issue.\n \n If you are accounting for `cd` failures in a way shellcheck doesn't realize, you can disable this message with a [[directive]].\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: This nested loop overrides the index variable of its parent. [SC2165]"},{"from": "gpt", "value": "## This nested loop overrides the index variable of its parent.\n \n And companion warning \"This parent loop has its index variable overridden.\"\n \n ### Problematic code:\n \n ```sh\n for((i=0; i<10; i++))\n do\n for i in *\n do\n echo \"$i\"\n done\n done\n ```\n \n ### Correct code:\n \n ```sh\n for((i=0; i<10; i++))\n do\n for j in *\n do\n echo \"$j\"\n done\n done\n ```\n \n ### Rationale:\n \n When nesting loops, especially arithmetic for loops, using the same loop variable can cause unexpected results.\n \n In the problematic code, `i` will contain the last filename from the inner loop, which will be interpreted as a value in the next iteration out the outer loop. This results in either an infinite loop or a syntax error, depending on whether the last filename is a valid shell variable name.\n \n In nested for-in loops, variable merely shadow each other and won't cause infinite loops or syntax errors, but reusing the variable name is rarely intentional.\n \n ### Exceptions:\n \n None.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Prefer `[ p ] && [ q ]` as `[ p -a q ]` is not well-defined. [SC2166]"},{"from": "gpt", "value": "## Prefer `[ p ] && [ q ]` as `[ p -a q ]` is not well-defined.\n \n And likewise, prefer `[ p ] || [ q ]` over `[ p -o q ]`.\n \n ### Problematic code:\n \n ```sh\n [ \"$1\" = \"test\" -a -z \"$2\" ]\n ```\n \n ### Correct code:\n \n ```sh\n [ \"$1\" = \"test\" ] && [ -z \"$2\" ]\n ```\n \n \n ### Rationale:\n \n `-a` and `-o` to mean AND and OR in a `[ .. ]` test expression is not well defined, and can cause incorrect results when arguments start with dashes or contain `!`. [From POSIX](http://pubs.opengroup.org/onlinepubs/9699919799/utilities/test.html):\n \n >The XSI extensions specifying the -a and -o binary primaries and the '(' and ')' operators have been marked obsolescent. (Many expressions using them are ambiguously defined by the grammar depending on the specific expressions being evaluated.) Scripts using these expressions should be converted to the forms given below. Even though many implementations will continue to support these obsolescent forms, scripts should be extremely careful when dealing with user-supplied input that could be confused with these and other primaries and operators. Unless the application developer knows all the cases that produce input to the script, invocations like:\n >\n > `test \"$1\" -a \"$2\"`\n >\n >should be written as:\n >\n > `test \"$1\" && test \"$2\"`\n \n \n Using multiple `[ .. ]` expressions with shell AND/OR operators `&&` and `||` is well defined and therefore preferred (but note that they have equal precedence, while `-a`/`-o` is unspecified but usually implemented as `-a` having higher precedence).\n \n ### Exceptions:\n \n If the shell variant being used is ksh derived (such as the bash shell) it will have the shell builtin command `[[ ... ]]`. This has the operators `&&`, `||`, `(`, `)`, `!` which safely avoid the ambiguity by noting which arguments were quoted and requiring the operators to be unquoted (except by the `[[ ... ]]` construct itself).\n \n ### See also:\n * [Problems With the test Builtin: What Does -a Mean?](http://www.oilshell.org/blog/2017/08/31.html)\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: This parent loop has its index variable overridden. [SC2167]"},{"from": "gpt", "value": "## This parent loop has its index variable overridden.\n \n See companion warning [[SC2165]].\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: `local` is only valid in functions. [SC2168]"},{"from": "gpt", "value": "## `local` is only valid in functions.\n \n ### Problematic code:\n \n ```sh\n local foo=bar\n echo \"$foo\"\n ```\n \n ### Correct code:\n \n ```sh\n foo=bar\n echo \"$foo\"\n ```\n ### Rationale:\n \n In Bash, `local` can only be used in functions. In other contexts, it's an error.\n \n ### Exceptions:\n \n It's possible to source files containing `local` from a function context but not from any other context. This is not good practice, but in these cases you can [[ignore]] this error.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: In dash, *something* is not supported. [SC2169]"},{"from": "gpt", "value": "## In dash, *something* is not supported.\n \n _Note: This warning has been retired in favor of individual SC3xxx warnings for each individual issue. Removed in [V0.7.2 - 2021-04-19](https://github.com/koalaman/shellcheck/commit/cfd68ee0c2ebfd0ab08a1d4bf628162b454dc207)_\n \n You are writing a script for `dash`, but you're using a feature that `dash` doesn't support. See [[SC2039]], the equivalent warning for POSIX sh, for possible workarounds.\n \n See also Ubuntu's [DashAsBinSh](https://wiki.ubuntu.com/DashAsBinSh) migration guide for how to make bash-specific scripts dash-compatible.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Invalid number for `-eq`. Use `=` to compare as string (or use `$var` to expand as a variable). [SC2170]"},{"from": "gpt", "value": "## Invalid number for `-eq`. Use `=` to compare as string (or use `$var` to expand as a variable).\n \n ### Problematic code:\n \n ```sh\n read -r n\n if [ n -lt 0 ]\n then\n echo \"bad input\"\n fi\n \n if [ \"$USER\" -eq root ]\n then\n echo \"You are root\"\n fi\n ```\n \n ### Correct code:\n \n ```sh\n read -r n\n if [ \"$n\" -lt 0 ] # Numerical comparison\n then\n echo \"bad input\"\n fi\n \n if [ \"$USER\" = root ] # String comparison\n then\n echo \"You are root\"\n fi\n ```\n ### Rationale:\n \n You are comparing a string value with a numerical operator, such as `-eq`, `-ne`, `-lt` or `-gt`. These only work for numbers.\n \n If you want to compare the value as a string, switch to the equivalent string operator: `=`, `!=` `\\<` or `\\>`.\n \n If you want to compare it as a number, such as `n=42; while [ n -gt 1024/8 ]; ..`, then keep the operator and expand the operands yourself with `$var` or `$((expr))`: `while [ \"$n\" -gt $((1024/8)) ]`\n \n ### Exceptions:\n \n None.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Found trailing `]` outside test. Add missing `[` or quote if intentional. [SC2171]"},{"from": "gpt", "value": "## Found trailing `]` outside test. Add missing `[` or quote if intentional.\n \n ### Problematic code:\n \n ```sh\n if foo -eq bar ]; then true; fi\n ```\n \n or\n \n ```sh\n tr -d ]\n ```\n \n ### Correct code:\n \n ```sh\n if [ foo -eq bar ]; then true; fi\n ```\n \n or\n \n ```sh\n tr -d ']'\n ```\n \n ### Rationale:\n \n ShellCheck found a non-test command that ends with `]` or `]]`.\n \n If this was intended to be a test expression like in the first example, add the missing `[` or `[[`. \n \n If the `]` was intended to be literal, like in `tr -d ]`, you can quote to make this obvious.\n \n ### Exceptions:\n \n `tr -d ]` is valid and not different from `tr -d ']'`, so in these cases you can ignore the error instead.\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Trapping signals by number is not well-defined. Prefer signal names. [SC2172]"},{"from": "gpt", "value": "## Trapping signals by number is not well-defined. Prefer signal names.\n \n ### Problematic code:\n \n ```sh\n trap myfunc 28\n ```\n \n ### Correct code:\n \n ```sh\n trap myfunc WINCH\n ```\n ### Rationale:\n \n Signal numbers can vary between platforms. Prefer signal names, which are fixed.\n \n Signal numbers 1, 2, 3, 6, 9, 14 and 15 are specified as parts of the optional POSIX XSI and ShellCheck will not warn about these. \n \n ### Exceptions:\n \n None.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: SIGKILL/SIGSTOP can not be trapped. [SC2173]"},{"from": "gpt", "value": "## SIGKILL/SIGSTOP can not be trapped.\n \n ### Problematic code:\n \n ```sh\n trap 'echo \"unkillable\"' KILL\n ```\n \n ### Correct code:\n \n Not applicable. This is not possible.\n \n ### Rationale:\n \n SIGKILL and SIGSTOP can not be caught/ignored (according to POSIX and as implemented on platforms including Linux and FreeBSD). Trying to trap this signal has undefined results.\n \n ### Exceptions:\n \n None. If you come across one, please file an issue about it.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: When used with `-p`, `-m` only applies to the deepest directory. [SC2174]"},{"from": "gpt", "value": "## When used with `-p`, `-m` only applies to the deepest directory.\n \n ### Problematic code:\n \n ```sh\n mkdir -p -m 0755 foo/bar/baz\n ```\n \n ### Correct code:\n \n ```sh\n mkdir -p foo/bar/baz\n chmod 0755 foo/bar/baz foo/bar foo\n ```\n \n ### Rationale:\n \n When using `-m 0755`, the mode of the directory created will be set to 0755. When using `-p`, parent directories which do not exist will be created, but the mode specified by `-m` will only be used on the last directory. The parent directories will get their access mode the default way, via [umask(2)].\n \n [umask(2)]: http://man7.org/linux/man-pages/man2/umask.2.html\n \n ### Exceptions:\n \n ShellCheck does not warn if the path only has one component, as in `mkdir -p -m 0755 mydir`, but will not attempt to determine whether this applies for a variable as in `mkdir -p -m 0755 \"$mydir\"`. You can mkdir/chmod separately or [[ignore]] this message.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Quote this invalid brace expansion since it should be passed literally to eval [SC2175]"},{"from": "gpt", "value": "## Quote this invalid brace expansion since it should be passed literally to eval\n \n ### Problematic code:\n \n ```sh\n eval echo {1..$n}\n ```\n \n ### Correct code:\n \n ```sh\n eval \"echo {1..$n}\"\n ```\n ### Rationale:\n \n Using `eval somecommand {1..$n}` depends both on bash silently failing to interpret the brace expansion, and on it passing failing brace expansions literally. \n \n Rather than depending on these questionable features (which already behave differently in other shells), use the explicit, predictable way of passing values literally: quoting.\n \n ### Exceptions:\n \n None. \n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: `time` is undefined for pipelines. time single stage or `bash -c` instead. [SC2176]"},{"from": "gpt", "value": "## `time` is undefined for pipelines. time single stage or `bash -c` instead.\n \n ### Problematic code:\n \n ```sh\n time foo | bar\n ```\n \n ### Correct code:\n \n To time the most relevant stage:\n \n ```sh\n foo | { time bar; }\n ```\n \n To time everything in a pipeline:\n \n ```sh\n time bash -c 'foo | bar'\n ```\n \n Note that you can not use `time sh -c` to time an entire pipeline, because POSIX does not guarantee that anything other than the last stage is waited upon by the shell. \n \n ### Rationale:\n \n This behavior is explicitly left undefined [in POSIX](http://pubs.opengroup.org/onlinepubs/9699919799/utilities/time.html).\n \n ### Exceptions:\n \n None. This warning is not emitted in `ksh` or `bash` where `time` is defined for pipelines.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: `time` is undefined for compound commands, use `time sh -c` instead. [SC2177]"},{"from": "gpt", "value": "## `time` is undefined for compound commands, use `time sh -c` instead.\n \n ### Problematic code:\n \n ```sh\n time for i in *.bmp; do convert \"$i\" \"$i.png\"; done\n ```\n \n ### Correct code:\n \n ```sh\n time sh -c 'for i in *.bmp; do convert \"$i\" \"$i.png\"; done'\n ```\n ### Rationale:\n \n `time` is only defined for Simple Commands [by POSIX](http://pubs.opengroup.org/onlinepubs/9699919799/utilities/time.html). Timing loops, command groups and similar is not.\n \n ### Exceptions:\n \n None. If you use a shell that supports this (e.g. bash, ksh), specify this shell in the shebang.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Variable was used as an array but is now assigned a string. [SC2178]"},{"from": "gpt", "value": "## Variable was used as an array but is now assigned a string.\n \n ### Problematic code:\n \n ```sh\n flags[0]=\"-r\"\n flags[1]=\"--delete-after\"\n \n if [ \"$dryrun\" ]\n then\n flags=\"--dry-run\"\n fi\n \n ```\n \n ### Correct code:\n \n ```sh\n flags[0]=\"-r\"\n flags[1]=\"--delete-after\"\n \n if [ \"$dryrun\" ]\n then\n flags=( \"--dry-run\" )\n fi\n ```\n ### Rationale:\n \n ShellCheck noticed that you have used a variable as an array, but then assign it a string. `array=foo` is equivalent to `array[0]=foo`, and leaves the rest of the elements unaffected.\n \n In the incorrect code, `\"${flags[@]}\"` would contain `--dry-run` `--delete-after`.\n \n To set an array to only a single, given element, you should use `array=( foo )`.\n \n In the correct code, `\"${flags[@]}\"` will contain `--dry-run` only. \n \n Another possible cause is accidentally missing the `$` on a previous assignment: `var=(my command); var=bar` instead of `var=$(my command); var=bar`. If the variable is not intended to be an array, ensure that it's never assigned as one.\n \n ### Bugs:\n \n There is a [known issue](https://github.com/koalaman/shellcheck/issues/1309) with this check's handling of `local` variables, causing ShellCheck to flag variables that were previously declared as arrays, even if they are in different scopes.\n \n The easiest workaround is to simply use different variable names. Alternatively, you can [[ignore]] the check.\n \n It is also possible to satisfy ShellCheck by declaring the `local` variable separately from assigning to it, e.g.:\n \n ```sh\n foo () {\n local -a baz\n baz+=(\"foo\" \"bar\")\n echo \"${baz[@]}\"\n }\n \n bar () {\n local baz # ShellCheck gets confused if these lines are merged as local baz=\"qux\"\n baz=\"qux\"\n echo \"$baz\"\n }\n ```\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Use `array+=(\"item\")` to append items to an array. [SC2179]"},{"from": "gpt", "value": "## Use `array+=(\"item\")` to append items to an array.\n \n ### Problematic code:\n \n ```sh\n var=(one two)\n var+=three\n ```\n \n ### Correct code:\n \n ```sh\n var=(one two)\n var+=( three )\n ```\n ### Rationale:\n \n It looks like you are trying to append a string to an array with `var+=string`. This instead appends to the first element of the array (equivalent to `var[0]+=three`).\n \n In the problematic code, the array will therefore contain `onethree` `two`.\n \n Instead, append an array to the array with `var+=( elements )`. This will append the new items to the array.\n \n In the correct code, it will contain `one` `two` `three` as expected.\n \n ### Exceptions:\n \n If ShellCheck mistakenly thinks the variable is an array when it's not (e.g. because the same name was used in a different context), you can ignore this error.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Bash does not support multidimensional arrays. Use 1D or associative arrays. [SC2180]"},{"from": "gpt", "value": "## Bash does not support multidimensional arrays. Use 1D or associative arrays.\n \n ### Problematic code:\n \n ```sh\n foo[1][2]=bar\n echo \"${foo[1][2]}\"\n ```\n \n ### Correct code:\n \n In bash4, consider using associative arrays:\n ```sh\n declare -A foo\n foo[1,2]=bar\n echo \"${foo[1,2]}\"\n ```\n \n Otherwise, do your own index arithmetic:\n ```sh\n size=10\n foo[1*size+2]=bar\n echo \"${foo[1*size+2]}\"\n ```\n \n ### Rationale:\n \n Bash does not support multidimensional arrays. Rewrite it to use 1D arrays. Associative arrays map arbitrary strings to values, and are therefore useful since you can construct keys like `\"1,2,3\"` or `\"val1;val2;val3\"` to index them.\n \n ### Exceptions:\n \n None.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Check exit code directly with e.g. `if mycmd;`, not indirectly with `$?`. [SC2181]"},{"from": "gpt", "value": "## Check exit code directly with e.g. `if mycmd;`, not indirectly with `$?`.\n \n ### Problematic code:\n \n ```sh\n make mytarget\n \n if [ $? -ne 0 ]\n then\n echo \"Build failed\"\n fi\n ```\n \n ### Correct code:\n \n ```sh\n if ! make mytarget\n then\n echo \"Build failed\"\n fi\n ```\n For the Solaris 10 Bourne shell:\n ```sh\n if make mytarget\n then\n :\n else\n echo \"Build failed\"\n fi\n ```\n \n ### Rationale:\n \n Running a command and then checking its exit status `$?` against 0 is redundant.\n \n Instead of just checking the exit code of a command, it checks the exit code of a command (e.g. `[`) that checks the exit code of a command.\n \n Apart from the redundancy, there are other reasons to avoid this pattern:\n \n * Since the command and its status test are decoupled, inserting an innocent command like `echo \"make finished\"` after `make` will cause the `if` statement to silently start comparing `echo`'s status instead.\n * Scripts that run or are called with `set -e ` aka `errexit` will exit immediately if the command fails, even though they're followed by a clause that handles failure. \n * The value of `$?` is overwritten by `[`/`[[`, so you can't get the original value in the relevant then/else block (e.g. `if mycmd; then echo \"Success\"; else echo \"Failed with $?\"; fi`).\n \n To check that a command returns success, use `if mycommand; then ...`.\n \n To check that a command returns failure, use `if ! mycommand; then ...`. Notice that `!` will overwrite `$?` value.\n \n To additionally capture output with command substitution: `if ! output=$(mycommand); then ...`\n \n This also applies to `while`/`until` loops.\n \n The default Solaris 10 Bourne shell does not support negating exit statuses with `!`, so `! mycommand` tries to invoke a utility named \"!\" instead. To test for failure, use `if mycommand; then :; else ...; fi` and `until mycommand; do ...; done`.\n \n ### Exceptions:\n \n None.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: This printf format string has no variables. Other arguments are ignored. [SC2182]"},{"from": "gpt", "value": "## This printf format string has no variables. Other arguments are ignored.\n \n ### Problematic code:\n \n ```sh\n place=\"world\"\n printf hello $place\n ```\n \n ### Correct code:\n \n ```sh\n place=\"world\"\n printf \"hello %s\\n\" \"$place\"\n ```\n ### Rationale:\n \n ShellCheck has noticed that you're using a `printf` with multiple arguments, but where the first argument has no `%s` or equivalent variable placeholders.\n \n `echo` accepts zero or more strings to write, e.g. `echo hello world`.\n \n `printf` instead accepts one pattern/template with zero or more `%s`-style placeholders, and one argument for each placeholder.\n \n Rewrite your command using the right semantics, otherwise all arguments after the first one will be ignored:\n \n $ printf hello world\\\\n\n hello\n \n $ printf \"hello world\\n\"\n hello world\n \n $ printf \"hello %s\\n\" \"world\"\n hello world\n \n ### Exceptions:\n \n If you wanted a no-op, use `:` instead.\n \n ```sh\n : ${place=world}\n ```\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: This format string has 2 variables, but is passed 1 argument. [SC2183]"},{"from": "gpt", "value": "## This format string has 2 variables, but is passed 1 argument.\n \n ### Problematic code:\n \n ```sh\n printf \"Hello %s, welcome to %s.\\n\" \"$USER\"\n ```\n \n ### Correct code:\n \n ```sh\n printf \"Hello %s, welcome to %s.\\n\" \"$USER\" \"$HOSTNAME\"\n ```\n ### Rationale:\n \n ShellCheck has noticed that you're using a `printf` format string with more `%s` variables than arguments to fill them.\n \n In the problematic example case, the last `%s` will just become an empty string every time.\n \n Either remove the unused variables from the format string, or add enough arguments to fill them.\n \n ### Exceptions:\n \n When using the Ksh/Bash `%T` timestamp extension, such as `printf 'The time is %(%H:%M)T\\n'`, an argument of `-1` and no argument are both taken to mean the current time. In these cases, consider specifying `-1` explicitly.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Quote arguments to unset so they're not glob expanded. [SC2184]"},{"from": "gpt", "value": "## Quote arguments to unset so they're not glob expanded.\n \n ### Problematic code:\n \n ```sh\n unset foo[index]\n ```\n \n ### Correct code:\n \n ```sh\n unset 'foo[index]'\n ```\n ### Rationale:\n \n Arguments to `unset` are subject to regular glob expansion. This is especially relevant when unsetting indices in arrays, where `[..]` is considered a glob character group.\n \n In the problematic code, having a file called `food` in the current directory will result in `unset foo[index]` expanding to `unset food`, which will silently succeed without unsetting the element.\n \n Quoting so that the `[..]` is passed literally to `unset` solves the issue.\n \n Note that you can unset element using variable for index name like this:\n \n ```sh\n unset 'foo[$var]'\n ```\n \n ### Exceptions:\n \n If you know that pathname expansion is disabled you can ignore this message. `set -o noglob` (and variations like invoking the script with `#!/bin/bash -f`) will prevent glob expansion of arguments to `unset`.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Some finds don't have a default path. Specify `.` explicitly. [SC2185]"},{"from": "gpt", "value": "## Some finds don't have a default path. Specify `.` explicitly.\n \n ### Problematic code:\n \n ```sh\n find -type f\n ```\n \n ### Correct code:\n \n ```sh\n find . -type f\n ```\n ### Rationale:\n \n When not provided a search path, GNU and Busybox `find` will use a default path of `.`, the current directory.\n \n On POSIX, macOS/OSX, FreeBSD, OpenBSD and NetBSD, it will instead result in an error.\n \n Explicitly specifying a path works across all implementations, and is therefore preferred.\n \n ### Exceptions:\n \n You will get a false positive if you concatenate a series of pre-path flags:\n \n find -XLE .\n \n In such cases, please either use `find -X -L -E .` or [[ignore]] the message.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: tempfile is deprecated. Use mktemp instead. [SC2186]"},{"from": "gpt", "value": "## tempfile is deprecated. Use mktemp instead.\n \n ### Problematic code:\n \n ```sh\n tmp=$(tempfile)\n ```\n \n ### Correct code:\n \n ```sh\n tmp=$(mktemp)\n ```\n ### Rationale:\n \n `tempfile` is a Debian specific utility for creating temporary files. Its man page notes:\n \n >tempfile is deprecated; you should use mktemp(1) instead.\n \n Neither `tempfile` nor `mktemp` are POSIX, but `tempfile` is Debian specific while `mktemp` works on GNU, OSX, BusyBox, *BSD and Solaris.\n \n ### Exceptions:\n \n ShellCheck will not recognize when a function overrides this name.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Ash scripts will be checked as Dash. Add `# shellcheck shell=dash` to silence. [SC2187]"},{"from": "gpt", "value": "## Ash scripts will be checked as Dash. Add `# shellcheck shell=dash` to silence.\n \n ### Problematic code:\n \n ```sh\n #!/bin/ash\n echo \"Hello World\"\n ```\n \n ### Correct code:\n \n ```sh\n #!/bin/ash\n # shellcheck shell=dash\n echo \"Hello World\"\n ```\n ### Rationale:\n \n ShellCheck has no first class support for `ash`, but it does support its Debian fork `dash` and defaults to this whenever `ash` is specified.\n \n Unfortunately, while the two are similar, they are not completely compatible. For example, `ash` supports `echo -e` but `dash` does not, so ShellCheck will incorrectly warn about it.\n \n You can use a [[directive]] to let ShellCheck know you're aware of this problem.\n \n ### Exceptions:\n \n None. \n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: This redirection doesn't have a command. Move to its command (or use `true` as no-op). [SC2188]"},{"from": "gpt", "value": "## This redirection doesn't have a command. Move to its command (or use `true` as no-op).\n \n ### Problematic code:\n \n ```sh\n { \n echo \"Report for $(date +%F)\"\n uptime\n df -h\n }\n > report.txt\n ```\n \n ### Correct code:\n \n ```sh\n { \n echo \"Report for $(date +%F)\"\n uptime\n df -h\n } > report.txt\n ```\n ### Rationale:\n \n ShellCheck found a redirection that doesn't actually redirect from/to anything.\n \n This could indicate a bug, such as in the problematic code where an additional linefeed causes `report.txt` to be truncated instead of containing report output, or in `foo & > bar`, where either `foo &> bar` or `foo > bar &` was intended. \n \n However, it could also be intentionally used to truncate a file or check that it's readable. You can make this more explicit for both ShellCheck and human readers by using `true` or `:` as a dummy command, e.g. `true > file` or `: > file`. \n \n ### Exceptions:\n \n There are no semantic problems with using `> foo` over `true > foo`, so if you don't see this as a potential source of bugs or confusion, you can [[ignore]] it.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: You can't have `|` between this redirection and the command it should apply to. [SC2189]"},{"from": "gpt", "value": "## You can't have `|` between this redirection and the command it should apply to.\n \n ### Problematic code:\n \n ```sh\n < file.txt | grep foo\n ```\n \n ### Correct code:\n \n ```sh\n < file.txt grep foo # or more canonically: grep foo < file.txt\n ```\n \n ### Rationale:\n \n ShellCheck has found a stage in a pipeline that consists of a redirection but no command. This doesn't make sense because a redirection without a command will not read or write any data.\n \n This is most likely to occur when deleting a command that had a redirection, but leaving a `|` behind instead of moving the redirection to a different command:\n \n ```\n # Match lines with line numbers\n nl < foo.txt | grep bar\n \n # Incorrect attempt at removing line numbers. grep now has no input:\n < foo.txt | grep bar\n \n # Line numbers correctly removed. grep now reads foo.txt as intended.\n grep bar < foo.txt\n ```\n \n ### Exceptions:\n \n It's technically valid to do e.g. `echo foo | > \"$(cat)\"` to truncate a file called \"foo\", but please consider rewriting such code.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Elements in associative arrays need index, e.g. `array=( [index]=value )` . [SC2190]"},{"from": "gpt", "value": "## Elements in associative arrays need index, e.g. `array=( [index]=value )` .\n \n ### Problematic code:\n \n ```sh\n declare -A foo\n foo=( myvalue )\n ```\n \n ### Correct code:\n \n ```sh\n declare -A foo\n foo=( [key]=myvalue )\n ```\n ### Rationale:\n \n You appear to be initializing or appending an array element to an associative array without giving it an index. In an indexed array, elements will be auto-indexed by incremented characters. In associative arrays, the index must be given explicitly.\n \n This could happen because of invalid spaces or otherwise malformed index assignment, such as `array=( [key] = value )`. This should instead be `array=( [key]=value )`.\n \n ### Exceptions:\n \n ShellCheck may be confused when a variable name is reused in different contexts. If shellcheck mistakenly believes the array is associated, please [[ignore]] this error. \n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: The `=` here is literal. To assign by index, use `( [index]=value )` with no spaces. To keep as literal, quote it. [SC2191]"},{"from": "gpt", "value": "## The `=` here is literal. To assign by index, use `( [index]=value )` with no spaces. To keep as literal, quote it.\n \n ### Problematic code:\n \n ```sh\n array=( [index] = value )\n ```\n \n ### Correct code:\n \n ```sh\n array=( [index]=value )\n ```\n \n ### Rationale:\n \n The shell doesn't care about the `=` sign in your array assignment because it's not part of a recognized index assignment. Instead, it's considered a literal character and becomes part of an array element's value.\n \n In the example problematic code, this is because the `=` was intended to set the index, but the shell will not recognize it when it is surrounded by spaces.\n \n Make sure to remove any spaces around the `=` when assigning by index, such as in the correct code.\n \n If you wanted the `=` to be a literal part of the array element, add quotes around it, such as `env=( \"LC_CTYPE=C\" )` or `specialChars=( \"=\" \"%\" \";\" )` .\n \n ### Exceptions:\n \n None. \n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: This array element has no value. Remove spaces after `=` or use `\"\"` for empty string. [SC2192]"},{"from": "gpt", "value": "## This array element has no value. Remove spaces after `=` or use `\"\"` for empty string.\n \n ### Problematic code:\n \n ```sh\n array=([1]=one [2]= two)\n ```\n \n ### Correct code:\n \n ```sh\n array=([1]=one [2]=two)\n ```\n ### Rationale:\n \n You have an array element on the form `[index]=`. The shell will interpret this as an independent element with index `index` and value ``.\n \n This may happen as part of the expression `[index]= value`, where the space is not allowed and causes the shell to interpret it as `[index]=\"\" [index+1]=value`.\n \n If you wanted the element to have a value, remove the spaces after `=`, e.g. `[index]=value`.\n \n If you wanted to assign an empty string, explicitly use empty quotes: `[index]=\"\"`. This makes no difference to the shell, but will make your intention clear to shellcheck and other humans. \n \n ### Exceptions:\n \n None.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: The arguments to this comparison can never be equal. Make sure your syntax is correct. [SC2193]"},{"from": "gpt", "value": "## The arguments to this comparison can never be equal. Make sure your syntax is correct.\n \n ### Problematic code:\n \n ```sh\n [ $var+1 == 5 ] # Unevaluated math\n [ \"{$var}\" == \"value\" ] # Swapped around $ and {\n [ \"$(cmd1) | cmd2\" == \"42\" ] # Ended with ) too soon\n [[ \"$var \" == *.png ]] # Trailing space\n ```\n \n ### Correct code:\n \n ```sh\n [ $((var+1)) == 5 ] # Evaluated math\n [ \"${var}\" == \"value\" ] # Correct variable expansion\n [ \"$(cmd1 | cmd2)\" == \"42\" ] # Correct command substitution\n [[ \"$var\" == *.png ]] # No trailing space\n ```\n ### Rationale:\n \n ShellCheck has determined that the two values you're comparing can never be equal. \n \n Most of the time, this happens because of a syntax issue that introduced unintended literal characters into one of the arguments.\n \n The left-hand side in the problematic examples will always contain (respectively) curly braces, pipe and trailing space. The right-hand sides are literal values and a pattern without trailing spaces, so they will never be equal. The statement is therefore useless, strongly indicating a bug. \n \n ### Exceptions:\n \n None.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: This word is constant. Did you forget the `$` on a variable? [SC2194]"},{"from": "gpt", "value": "## This word is constant. Did you forget the `$` on a variable?\n \n ### Problematic code:\n \n ```sh\n case foo in\n bar) echo \"Match\"\n esac\n ```\n \n ### Correct code:\n \n ```sh\n case $foo in\n bar) echo \"Match\"\n esac\n ```\n ### Rationale:\n \n You are using a `case` statement to compare a literal word.\n \n You most likely wanted to treat this word as a `$variable` or `$(command)` instead.\n \n ### Exceptions:\n \n None\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: This pattern will never match the case statement's word. Double check them. [SC2195]"},{"from": "gpt", "value": "## This pattern will never match the case statement's word. Double check them.\n \n ### Problematic code:\n \n ```sh\n case \"$var \" in # Trailing space\n value) echo \"Match\"\n esac\n ```\n \n ### Correct code:\n \n ```sh\n case \"${var}\" in # No trailing space\n value) echo \"Match\"\n esac\n ```\n ### Rationale:\n \n ShellCheck has detected that one of the patterns in a `case` statement will never match. \n \n Often, this is due to mistakes in the case statement word that results in unintended literal characters. In the problematic code, there's a trailing space that will prevent the match from ever succeeding.\n \n For more examples of when this could happen, see [SC2193](https://github.com/koalaman/shellcheck/wiki/SC2193) for the equivalent warning for `[[ .. ]]` statements.\n \n Note that ShellCheck warns about individual patterns in a branch, and will flag `*.png` in this example even though the branch is not dead:\n \n ```\n case \"${img}.jpg\" in\n *.png | *.jpg) echo \"It's an image\"\n esac\n ```\n \n ### Exceptions:\n \n None. If you encounter a bug and wish to [[ignore]] this warning, make sure the directive goes in front of the `case` and not the individual branch. \n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: `egrep` is non-standard and deprecated. Use `grep -E` instead. [SC2196]"},{"from": "gpt", "value": "## `egrep` is non-standard and deprecated. Use `grep -E` instead.\n \n ### Problematic code:\n \n ```sh\n egrep 'foo|bar' file\n ```\n \n ### Correct code:\n \n ```sh\n grep -E 'foo|bar' file\n ```\n ### Rationale:\n \n `egrep` is a non-standard command. Its functionality is provided in POSIX by `grep -E`. [POSIX grep](http://pubs.opengroup.org/onlinepubs/9699919799/utilities/grep.html) says:\n \n >This grep has been enhanced in an upwards-compatible way to provide the exact functionality of the historical egrep and fgrep commands as well. It was the clear intention of the standard developers to consolidate the three greps into a single command.\n \n man grep for GNU says:\n \n >Direct invocation as either egrep or fgrep is deprecated\n \n ### Exceptions:\n \n ShellCheck will fail to recognize when functions override `egrep`. Consider giving it a different name or [[ignore]] this error. \n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: `fgrep` is non-standard and deprecated. Use `grep -F` instead. [SC2197]"},{"from": "gpt", "value": "## `fgrep` is non-standard and deprecated. Use `grep -F` instead.\n \n ### Problematic code:\n \n ```sh\n fgrep '*.*' file\n ```\n \n ### Correct code:\n \n ```sh\n grep -F '*.*' file\n ```\n ### Rationale:\n \n `fgrep` is a non-standard command. Its functionality is provided in POSIX by `grep -F`. [POSIX grep](http://pubs.opengroup.org/onlinepubs/9699919799/utilities/grep.html) says:\n \n >This grep has been enhanced in an upwards-compatible way to provide the exact functionality of the historical egrep and fgrep commands as well. It was the clear intention of the standard developers to consolidate the three greps into a single command.\n \n man grep for GNU says:\n \n >Direct invocation as either egrep or fgrep is deprecated\n \n ### Exceptions:\n \n ShellCheck will fail to recognize when functions override `fgrep`. Consider giving it a different name or [[ignore]] this error. \n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Arrays don't work as operands in `[ ]`. Use a loop (or concatenate with `*` instead of `@`). [SC2198]"},{"from": "gpt", "value": "## Arrays don't work as operands in `[ ]`. Use a loop (or concatenate with `*` instead of `@`).\n \n ### Problematic code:\n \n ```sh\n ext=png\n allowedExt=(jpg bmp png)\n [ \"$ext\" = \"${allowedExt[@]}\" ] && echo \"Extension is valid\"\n ```\n \n ### Correct code:\n \n ```sh\n ext=png\n allowedExt=(jpg bmp png)\n for value in \"${allowedExt[@]}\"\n do\n [ \"$ext\" = \"$value\" ] && echo \"Extension is valid\"\n done\n ```\n ### Rationale:\n \n Array expansions become a series of words in `[ .. ]`. Operators expect single words only.\n \n The problematic code is equivalent to `[ \"$ext\" = jpg bmp png ]`, which is invalid syntax. A typical error message is `bash: [: too many arguments` or `dash: somefile: unexpected operator`. \n \n Instead, use a `for` loop to iterate over values, and apply your condition to each.\n \n Alternatively, if you want to concatenate all the values in the array into a single string for your test, use `\"$*\"` or `\"${array[*]}\"`.\n \n ### Exceptions:\n \n If you are dynamically building an a test expression, make your array the only thing in the test expression. ShellCheck will not emit a warning for: `set -- 1 -lt 2; [ \"$@\" ]`\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Arrays implicitly concatenate in `[[ ]]`. Use a loop (or explicit `*` instead of `@`). [SC2199]"},{"from": "gpt", "value": "## Arrays implicitly concatenate in `[[ ]]`. Use a loop (or explicit `*` instead of `@`).\n ### Problematic code:\n \n ```sh\n ext=png\n allowedExt=(jpg bmp png)\n [[ \"$ext\" = \"${allowedExt[@]}\" ]] && echo \"Extension is valid\"\n ```\n \n ### Correct code:\n \n ```sh\n ext=png\n allowedExt=(jpg bmp png)\n for value in \"${allowedExt[@]}\"\n do\n [[ \"$ext\" = \"$value\" ]] && echo \"Extension is valid\"\n done\n ```\n ### Rationale:\n \n Array expansions in `[[ .. ]]` will implicitly concatenate into a single string, much like in assignments. The problematic code is equivalent to `[ \"$ext\" = \"jpg bmp png\" ]`. \n \n Instead, use a `for` loop to iterate over values, and apply your condition to each.\n \n Alternatively, if you do want to concatenate all the values in the array into a single string for your test, use `\"$*\"` or `\"${array[*]}\"` to make this explicit.\n \n ### Exceptions:\n \n None.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Brace expansions don't work as operands in `[ ]`. Use a loop. [SC2200]"},{"from": "gpt", "value": "## Brace expansions don't work as operands in `[ ]`. Use a loop.\n \n ### Problematic code:\n \n ```sh\n [ \"$file\" = index.{htm,html,php} ] && echo \"This is the main file\"\n \n ```\n \n ### Correct code:\n \n ```sh\n for main in index.{htm,html,php}\n do\n [ \"$file\" = \"$main\" ] && echo \"This is the main file\"\n done\n ```\n \n ### Rationale:\n \n Brace expansions in `[ ]` will expand to a sequence of words. Operators work on single words.\n \n The problematic code is equivalent to `[ \"$file\" = index.htm index.html index.php ]`, which is invalid syntax. A typical error message is `bash: [: too many arguments` or `dash: somefile: unexpected operator`. \n \n Instead, use a `for` loop to iterate over values, and apply your condition to each.\n \n ### Exceptions:\n \n None.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Brace expansion doesn't happen in `[[ ]]`. Use a loop. [SC2201]"},{"from": "gpt", "value": "## Brace expansion doesn't happen in `[[ ]]`. Use a loop.\n \n ### Problematic code:\n \n ```sh\n [[ \"$file\" = index.{htm,html,php} ]] && echo \"This is the main file\"\n ```\n \n ### Correct code:\n \n ```sh\n for main in index.{htm,html,php}\n do\n [[ \"$file\" = \"$main\" ]] && echo \"This is the main file\"\n done\n ```\n \n ### Rationale:\n \n Brace expansions doesn't happen in `[[ ]]`. They will just be interpreted literally.\n \n Instead, use a `for` loop to iterate over values, and apply your condition to each.\n \n ### Exceptions:\n \n None.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Globs don't work as operands in `[ ]`. Use a loop. [SC2202]"},{"from": "gpt", "value": "## Globs don't work as operands in `[ ]`. Use a loop.\n \n ### Problematic code:\n \n ```sh\n [ current.log -nt backup/*.log ] && echo \"This is the latest file\"\n \n ```\n \n ### Correct code:\n \n ```sh\n newerThanAll=true\n for log in backup/*.log\n do\n [ current.log -nt \"$log\" ] || newerThanAll=false\n done\n [ \"$newerThanAll\" = \"true\" ] && echo \"This is the latest file\"\n ```\n \n ### Rationale:\n \n Globs in `[ ]` will expand to a sequence of words, one per matching filename. Meanwhile, operators work on single words.\n \n The problematic code is equivalent to `[ current.log -nt backup/file1.log backup/file2.log backup/file3.log ]`, which is invalid syntax. A typical error message is `bash: [: too many arguments` or `dash: somefile: unexpected operator`. \n \n Instead, use a `for` loop to iterate over matching filenames, and apply your condition to each.\n \n ### Exceptions:\n \n If you know your glob will only ever match one file, you can check this explicitly and use the first file:\n \n ```\n set -- backup/*.log\n [ $# -eq 1 ] || { echo \"There are too many matches.\"; exit 1; }\n [ file.log -nt \"$1\" ] && echo \"This is the latest file\"\n ```\n \n Alternatively, [[ignore]] this warning.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Globs are ignored in `[[ ]]` except right of `=`/`!=`. Use a loop. [SC2203]"},{"from": "gpt", "value": "## Globs are ignored in `[[ ]]` except right of `=`/`!=`. Use a loop.\n \n ### Problematic code:\n \n ```sh\n [[ current.log -nt backup/*.log ]] && echo \"This is the latest file\"\n \n ```\n \n ### Correct code:\n \n ```sh\n newerThanAll=true\n for log in backup/*.log\n do\n [[ current.log -nt \"$log\" ]] || newerThanAll=false\n done\n [[ \"$newerThanAll\" = \"true\" ]] && echo \"This is the latest file\"\n ```\n \n ### Rationale:\n \n Globs in `[[ ]]` will not filename expand, and will be treated literally (or as patterns on the right-hand side of `=`, `==` and `!=`).\n \n The problematic code is equivalent to `[[ current.log -nt 'backup/*.png' ]`, and will look for a file with a literal asterisk in the name.\n \n Instead, you can iterate over the filenames you want with a loop, and apply your condition to each filename.\n \n ### Exceptions:\n \n None.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: `(..)` is a subshell. Did you mean `[ .. ]`, a test expression? [SC2204]"},{"from": "gpt", "value": "## `(..)` is a subshell. Did you mean `[ .. ]`, a test expression?\n \n ### Problematic code:\n \n ```sh\n if ( -d mydir )\n then\n echo \"It's a directory\"\n fi\n ```\n \n ### Correct code:\n \n ```sh\n if [ -d mydir ]\n then\n echo \"It's a directory\"\n fi\n ```\n ### Rationale:\n \n Tests like `-d` to see if something is a directory or `-z` to see if it's non-empty are actually flags to the `test` command, and only work as tests in that context. `[` is an alias for `test`, so you'll frequently see them written as `[ -d mydir ]`.\n \n `( .. )` is completely unrelated, and is a subshell mostly used to scope shell modifications. They should not be used in `if` or `while` statements in shell scripts.\n \n If you wanted to test a condition, rewrite the `( .. )` to `[ .. ]`. \n \n ### Exceptions:\n \n None. \n \n This error is triggered by having a unary test operator as the first command name in a subshell, which won't normally happen. Note that there's a similar warning [[SC2205]] with a higher false positive rate.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: `(..)` is a subshell. Did you mean `[ .. ]`, a test expression? [SC2205]"},{"from": "gpt", "value": "## `(..)` is a subshell. Did you mean `[ .. ]`, a test expression?\n \n ### Problematic code:\n \n ```sh\n if ( 1 -lt 2 )\n then\n echo \"1 is less than 2\"\n fi\n ```\n \n ### Correct code:\n \n ```sh\n if [ 1 -lt 2 ]\n then\n echo \"1 is less than 2\"\n fi\n ```\n ### Rationale:\n \n Tests like `-eq` to check numeric equality or `\\<` for string comparison only work are actually parameters to the `test` command, and only work as tests in that context. `[` is an alias for `test`, so you'll frequently see them written as `[ 1 -eq 2 ]`.\n \n `( .. )` is completely unrelated, and is a subshell mostly used to scope shell modifications. They should not be used in `if` or `while` statements in shell scripts.\n \n If you wanted to test a condition, rewrite the `( .. )` to `[ .. ]`. \n \n ### Exceptions:\n \n This error is triggered by having a binary operator as the first parameter in a subshell, and could falsely trigger on e.g. `if ( grep -eq \"foo|bar\" file )`. In these cases, check whether the subshell is actually needed.\n \n Note that there's a similar looking error [[SC2204]] with a low false positive rate.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Quote to prevent word splitting/globbing, or split robustly with mapfile or `read -a`. [SC2206]"},{"from": "gpt", "value": "## Quote to prevent word splitting/globbing, or split robustly with mapfile or `read -a`.\n \n ### Problematic code:\n \n ```sh\n array=( $var )\n ```\n \n ### Correct code:\n \n If the variable should be a single element:\n \n ```sh\n array=( \"$var\" )\n ```\n \n If it's multiple lines, each of which should be an element:\n \n ```sh\n # For bash\n mapfile -t array <<< \"$var\"\n \n # For ksh\n printf '%s\\n' \"$var\" | while IFS=\"\" read -r line; do array+=(\"$line\"); done\n ```\n \n If it's a line with multiple words (separated by spaces, other delimiters can be chosen with IFS), [each of which should be an element](https://stackoverflow.com/a/30212526):\n \n ```sh\n # For bash\n IFS=\" \" read -r -a array <<< \"$var\"\n \n # For ksh\n IFS=\" \" read -r -A array <<< \"$var\"\n ``` \n \n ### Rationale:\n \n You are expanding a variable unquoted in an array. This will invoke the shell's sloppy word splitting and glob expansion.\n \n Instead, prefer explicitly splitting (or not splitting):\n \n * If the variable should become a single array element, quote it.\n * If you want to split into lines or words, use `mapfile`, `read -ra` and/or `while` loops as appropriate.\n \n This prevents the shell from doing unwanted splitting and glob expansion, and therefore avoiding problems with data containing spaces or special characters.\n \n ### Exceptions:\n \n If you have already taken care (through setting IFS and `set -f`) to have word splitting work the way you intend, you can [[ignore]] this warning.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Prefer `mapfile` or `read -a` to split command output (or quote to avoid splitting). [SC2207]"},{"from": "gpt", "value": "## Prefer `mapfile` or `read -a` to split command output (or quote to avoid splitting).\n \n ### Problematic code:\n \n ```sh\n array=( $(mycommand) )\n ```\n \n ### Correct code:\n \n If it outputs multiple lines, each of which should be an element:\n \n ```sh\n # For bash 4.4+, must not be in posix mode, may use temporary files\n mapfile -t array < <(mycommand)\n \n # For bash 3.x+, must not be in posix mode, may use temporary files\n array=()\n while IFS='' read -r line; do array+=(\"$line\"); done < <(mycommand)\n \n # For ksh, and bash 4.2+ with the lastpipe option enabled (may require disabling monitor mode)\n array=()\n mycommand | while IFS=\"\" read -r line; do array+=(\"$line\"); done\n ```\n \n If it outputs a line with multiple words (separated by spaces, other delimiters can be chosen with IFS), each of which should be an element:\n \n ```sh\n # For bash, uses temporary files\n IFS=\" \" read -r -a array <<< \"$(mycommand)\"\n \n # For bash 4.2+ with the lastpipe option enabled (may require disabling monitor mode)\n array=()\n mycommand | IFS=\" \" read -r -a array\n \n # For ksh\n IFS=\" \" read -r -A array <<< \"$(mycommand)\"\n ```\n \n If the output should be a single element:\n \n ```sh\n array=( \"$(mycommand)\" )\n ```\n \n ### Rationale:\n \n You are doing unquoted command expansion in an array. This will invoke the shell's sloppy word splitting and glob expansion.\n \n Instead, prefer explicitly splitting (or not splitting):\n \n * If you want to split the output into lines or words, use `mapfile`, `read -ra` and/or `while` loops as appropriate.\n * If the command output should become a single array element, quote it.\n \n This prevents the shell from doing unwanted splitting and glob expansion, and therefore avoiding problems with output containing spaces or special characters.\n \n ### Exceptions:\n \n If you have already taken care (through setting IFS and `set -f`) to have word splitting work the way you intend, you can ignore this warning.\n \n Another exception is the wish for error handling: `array=( $(mycommand) ) || die-with-error` works the way it looks while a similar `mapfile` construct like `mapfile -t array < <(mycommand)` **doesn't fail** and you will have to write more code for error handling.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Use `[[ ]]` or quote arguments to `-v` to avoid glob expansion. [SC2208]"},{"from": "gpt", "value": "## Use `[[ ]]` or quote arguments to `-v` to avoid glob expansion.\n \n ### Problematic code:\n \n ```sh\n [ -v foo[0] ] \n ```\n \n ### Correct code:\n \n ```sh\n [ -v 'foo[0]' ]\n ```\n ### Rationale:\n \n With `[`, arguments will undergo glob expansion. If a file `foo0` exists when the problematic code is run, it will check for the variable `foo0` instead of the array entry `foo[0]`. If there additionally exists a `foo1`, it will simply fail with an error.\n \n Use `[[ ]]` or quote the argument.\n \n ### Exceptions:\n \n None.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Use `var=$(command)` to assign output (or quote to assign string). [SC2209]"},{"from": "gpt", "value": "## Use `var=$(command)` to assign output (or quote to assign string).\n \n ### Problematic code:\n \n ```sh\n user=whoami # Want to run whoami and assign output\n \n PAGER=cat git log # Want to assign the string \"cat\"\n ```\n \n ### Correct code:\n \n ```sh\n user=$(whoami)\n \n PAGER=\"cat\" git log\n ```\n \n ### Rationale:\n \n Putting `var=` in front of a command will not assign its output. Use `var=$(my command here)` to execute the command and capture its output.\n \n If you do want to assign a literal string, use quotes to make this clear to shellcheck and humans alike. \n \n ### Exceptions:\n \n None. \n \n Quoting a single command (as in `PAGER=\"cat\"` above) doesn't change how the script works. It's purely to show shellcheck (and humans) that a literal assignment of a command name is intentional. \n \n This warning triggers generally when a variable is assigned an unquoted command name (from a list of hard coded names). See related warning [[SC2037]] which detects the same kind of error through the patterns `var=value -flag` and `var=value *glob*`.\n \n ### Related resources:\n \n * [BashFaq: How can I store the return value and/or output of a command in a variable?](https://mywiki.wooledge.org/BashFAQ/002)\n * [StackOverflow: How to set a variable to the output from a command in Bash](https://stackoverflow.com/questions/4651437/how-to-set-a-variable-to-the-output-from-a-command-in-bash)\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: This is a file redirection. Was it supposed to be a comparison or fd operation? [SC2210]"},{"from": "gpt", "value": "## This is a file redirection. Was it supposed to be a comparison or fd operation?\n \n ### Problematic code:\n \n ```sh\n if x > 5; then echo \"true\"; fi\n ```\n or\n ```sh\n foo > /dev/null 2>1\n ```\n \n ### Correct code:\n \n ```sh\n if (( x > 5 )); then echo \"true\"; fi\n ```\n or\n ```sh\n foo > /dev/null 2>&1\n ```\n ### Rationale:\n \n You are redirecting to or from a filename that is an integer. For example, `ls > file` where `file` happens to be `3`.\n \n This is not likely to be intentional. The most common causes are:\n \n 1. Trying to compare two numbers, as in `x > 5`. This should instead be `[ \"$x\" -gt 5 ]` or `(( x > 5 ))`.\n 1. Trying similarly to compare command output, as in `grep -c foo file > 100` instead of `[ \"$(grep -c foo file)\" -gt 100 ]`\n 1. Malformed FD operations, such as writing `1>2` instead of `1>&2`.\n \n If you do want to create a file named `4`, you can quote it to silence shellcheck and make it more clear to humans that it's not supposed to be taken numerically.\n \n ### Exceptions:\n \n If you use the `&>` form of redirection, as in `foo > /dev/null 2&>1`, it will trigger this warning. You can safely ignore this warning if that is what triggered it, or change your redirection operator to the semantically preferable `>&`.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: This is a glob used as a command name. Was it supposed to be in `${..}`, array, or is it missing quoting? [SC2211]"},{"from": "gpt", "value": "## This is a glob used as a command name. Was it supposed to be in `${..}`, array, or is it missing quoting?\n \n ### Problematic code:\n \n ```sh\n for f in $(*.png); do echo \"$f\"; done # Trying to loop over a glob\n array=$(*.txt) # Trying to assign an array\n echo \"$(array[1])\" # Trying to expand an array\n ```\n \n ### Correct code:\n \n ```sh\n for f in *.png; do echo \"$f\"; done\n array=(*.txt)\n echo \"${array[1]}\"\n ```\n \n ### Rationale:\n \n You are using a glob as a command name. This is usually a mistake caused by one of the following:\n \n * Trying to use `` `*foo*` `` or `$(*foo*)` to expand a glob. \n * Using `var=$(*.txt)` instead of `var=(*.txt)` to assign an array.\n * Using `$(..)` instead of `${..}` when expanding an array element.\n * Running a program with a name or directory that contains glob characters without escaping them.\n \n Look up and double check the syntax of what you're trying to do.\n \n ### Exceptions:\n \n None. If you want to specify a command name via glob, e.g. to not hard code version in `./myprogram-*/foo`, expand to array or parameters first to allow handling the cases of 0 or 2+ matches. \n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Use `false` instead of empty `[`/`[[` conditionals. [SC2212]"},{"from": "gpt", "value": "## Use `false` instead of empty `[`/`[[` conditionals.\n \n ### Problematic code:\n \n ```sh\n if [ ]\n then\n echo \"Temporarily disabled\"\n fi\n ```\n \n ### Correct code:\n \n ```sh\n if false\n then\n echo \"Temporarily disabled\"\n fi\n ```\n ### Rationale:\n \n `[ ]` is a somewhat obscure way of expressing falsehood, and the behavior is likely intended to allow the incorrectly quoted command `[ $var ]` to still work when the variable is unset.\n \n POSIX has a more descriptive command `false` for this.\n \n ### Exceptions:\n \n None. This is a stylistic suggestion, and has no effect on how the script works.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: getopts specified `-n`, but it's not handled by this `case`. [SC2213]"},{"from": "gpt", "value": "## getopts specified `-n`, but it's not handled by this `case`.\n \n ### Problematic code:\n \n ```sh\n while getopts \"vrn\" n\n do\n case \"$n\" in\n v) echo \"Verbose\" ;;\n r) echo \"Recursive\" ;;\n \\?) usage;;\n esac\n done\n ```\n \n ### Correct code:\n \n ```sh\n while getopts \"vrn\" n\n do\n case \"$n\" in\n v) echo \"Verbose\" ;;\n r) echo \"Recursive\" ;;\n n) echo \"Dry-run\" ;; # -n handled here\n \\?) usage;;\n esac\n done\n ```\n ### Rationale:\n \n You have a `while getopts` loop where the corresponding `case` statement fails to handle one of the flags.\n \n Either add a case to handle the flag, or remove it from the `getopts` option string.\n \n ### Exceptions:\n \n ShellCheck may not correctly recognize less canonical uses of `while getopts ..; do case ..;`, such as when modifying the variable before using it:\n \n ```\n while getopts \"rf-:\" OPT; do\n if [ \"$OPT\" = \"-\" ]; then # long option: reformulate OPT and OPTARG\n OPT=\"${OPTARG%%=*}\" # extract long option name\n OPTARG=\"${OPTARG#$OPT}\" # extract long option argument (may be empty)\n OPTARG=\"${OPTARG#=}\" # if long option argument, remove assigning `=`\n fi\n \n case \"$OPT\" in\n r) ... ;;\n f) ... ;;\n my-long-option) ... ;;\n esac\n done\n ```\n \n In such cases you can do one of:\n \n * [[Ignore]] the warning.\n * Use the external tool `getopt` (no \"s\") which supports long options natively.\n * Rewrite to not modify the variable first, in this case by instead doing it in a `-)` branch.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: This case is not specified by getopts. [SC2214]"},{"from": "gpt", "value": "## This case is not specified by getopts.\n \n ### Problematic code:\n \n ```sh\n while getopts \"vr\" n\n do\n case \"$n\" in\n v) echo \"Verbose\" ;;\n r) echo \"Recursive\" ;;\n n) echo \"Dry-run\" ;;\n *) usage;;\n esac\n done\n ```\n \n ### Correct code:\n \n ```sh\n while getopts \"vrn\" n # 'n' added here\n do\n case \"$n\" in\n v) echo \"Verbose\" ;;\n r) echo \"Recursive\" ;;\n n) echo \"Dry-run\" ;;\n *) usage;;\n esac\n done\n ```\n ### Rationale:\n \n You have a `case` statement in a `while getopts` loop that matches a flag that hasn't been provided in the `getopts` option string.\n \n Either add the flag to the options list, or delete the case statement.\n \n ### Exceptions:\n \n None.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: This flag is used as a command name. Bad line break or missing `[ .. ]`? [SC2215]"},{"from": "gpt", "value": "## This flag is used as a command name. Bad line break or missing `[ .. ]`?\n \n ### Problematic code:\n \n ```sh\n if -e .bashrc\n then\n echo \".bashrc already exists\"\n fi\n ```\n \n or\n \n ```sh\n find . -name '*.mkv'\n -exec mplayer {} \\;\n ```\n \n ### Correct code:\n \n ```sh\n if [ -e .bashrc ]\n then\n echo \".bashrc already exists\"\n fi\n ```\n \n or\n \n ```sh\n find . -name '*.mkv' \\\n -exec mplayer {} \\;\n ```\n ### Rationale:\n \n You are using a name that starts with a dash as a command name. This is almost always a bug.\n \n There are two typical ways in which this happens:\n \n * Missing `[ .. ]` or `[[ .. ]]` around a test expression, like in the first example example. \n * An invalid line break that splits a command in two, like in the second example.\n \n ### Exceptions:\n \n If you actually have a command that starts with a dash—which you should really reconsider—you can quote the name (or at least the leading dash). This makes no difference to the shell, but makes it clear to ShellCheck and humans that this is not intended as a flag.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Piping to `rm`, a command that doesn't read stdin. Wrong command or missing `xargs`? [SC2216]"},{"from": "gpt", "value": "## Piping to `rm`, a command that doesn't read stdin. Wrong command or missing `xargs`?\n \n ### Problematic code:\n \n ```sh\n ls | echo # Want to print result\n cat files | rm # Want to delete items from a file\n find . -type f | cp dir # Want to process 'find' output\n rm file | true # Want to ignore errors\n ```\n \n ### Correct code:\n \n ```sh\n ls\n cat files | while IFS= read -r file; do rm -- \"$file\"; done\n find . -type f -exec cp {} dir \\;\n rm file || true\n ```\n \n ### Rationale:\n \n You are piping to one of several commands that don't read from stdin.\n \n This may happen when:\n \n * Confusing one command for another, e.g. using `echo` where `cat` was intended.\n * Incorrectly refactoring, leaving a `|` on the previous line.\n * Missing `xargs`, because stdin should be passed as positional parameters instead (use `xargs -0` if at all possible).\n * Intending to use `||` instead of `|`\n \n Check your logic, and rewrite the command so data is passed correctly.\n \n ### Exceptions:\n \n If you've overridden a command to return output, you can either rename it to make this obvious, or [[ignore]] this message.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Redirecting to `echo`, a command that doesn't read stdin. Bad quoting or missing `xargs`? [SC2217]"},{"from": "gpt", "value": "## Redirecting to `echo`, a command that doesn't read stdin. Bad quoting or missing `xargs`?\n \n ### Problematic code:\n \n ```sh\n echo << eof\n Hello World\n eof\n ```\n \n ### Correct code:\n \n ```sh\n cat << eof\n Hello World\n eof\n ```\n \n ### Rationale:\n \n You are redirecting to one of several commands that don't read from stdin.\n \n This may happen when:\n \n * Confusing one command for another, e.g. using `echo` where `cat` was intended.\n * Incorrectly quoting angle brackets, e.g. using `echo

Hello` which tries to read from a file `p`.\n * Missing `xargs`, e.g. `mv -t dir < files` instead of `xargs mv -t dir < files` (or more safely, `tr '\\n' '\\0' < files | xargs -0 mv -t dir`), because stdin should be passed as parameters.\n \n Check your logic, and rewrite the command so data is passed correctly.\n \n ### Exceptions:\n \n If you've overridden a command to return output, you can either rename it to make this obvious, or [[ignore]] this message.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: This function is only defined later. Move the definition up. [SC2218]"},{"from": "gpt", "value": "## This function is only defined later. Move the definition up.\n \n ### Problematic code:\n \n ```sh\n #!/bin/sh\n myfunction\n \n myfunction() {\n echo \"Hello World\"\n }\n ```\n \n ### Correct code:\n \n ```sh\n #!/bin/sh\n myfunction() {\n echo \"Hello World\"\n }\n myfunction\n ```\n \n ### Rationale:\n \n You are calling a function that you are defining later in the file. The function definition must come first.\n \n Function definitions are much like variable assignments, and define a name at the point the definition is \"executed\". This is why they must happen before their first use.\n \n This is especially apparent when defining functions conditionally:\n \n ```\n case \"$(uname -s)\" in\n Linux) hi() { echo \"Hello from Linux\"; } ;;\n Darwin) hi() { echo \"Hello from macOS\"; } ;;\n *) hi() { echo \"Hello from something else\"; } ;;\n esac\n \n hi\n ```\n \n \n ### Exceptions:\n \n None. \n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Instead of `let expr`, prefer `(( expr ))` . [SC2219]"},{"from": "gpt", "value": "## Instead of `let expr`, prefer `(( expr ))` .\n \n ### Problematic code:\n \n ```sh\n let a++\n ```\n \n ### Correct code:\n \n ```sh\n (( a++ )) || true\n ```\n \n > Note, `|| true` bits ignore error status code when incrementing from `0` to `1`\n \n ### Rationale:\n \n The `(( .. ))` arithmetic compound command evaluates expressions in the same way as `let`, except it's not subject to glob expansion and therefore requires no additional quoting or escaping. \n \n This warning only triggers in Bash/Ksh scripts. In Sh/Dash, neither `let` nor `(( .. ))` are defined, but can be simulated with `[ $(( expr )) -ne 0 ]` to retain exit code, or `: $(( expr ))` to ignore it. For portability, the `$(( expr ))` syntax is defined in POSIX standard.\n \n ### Exceptions:\n \n None.\n \n ### More information\n \n * Bash Hacker's Wiki: [The let builtin command](https://web.archive.org/web/20230224010517/http://wiki.bash-hackers.org/commands/builtin/let)\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Invalid flags are not handled. Add a `*)` case. [SC2220]"},{"from": "gpt", "value": "## Invalid flags are not handled. Add a `*)` case.\n \n ### Problematic code:\n \n ```sh\n #!/bin/sh\n while getopts \"vr\" f\n do\n case \"$f\" in\n v) echo \"verbose\" ;;\n r) echo \"recursive\" ;;\n esac\n done\n ```\n \n ### Correct code:\n \n ```sh\n #!/bin/sh\n while getopts \"vr\" f\n do\n case \"$f\" in\n v) echo \"verbose\" ;;\n r) echo \"recursive\" ;;\n *) echo \"usage: $0 [-v] [-r]\" >&2\n exit 1 ;;\n esac\n done\n ```\n \n ### Rationale:\n \n The `case` statement handling `getopts` arguments does not have a default branch to handle unknown flags.\n \n When a flag is not recognized, such as if passing `-Z` to the example code, `getopts` will set the variable to a literal question mark `?`. This should be handled along with all the valid flags, usually by printing a usage message and exiting with failure.\n \n Using a `\\?)` or `?)` case will also match invalid flags, but`*)` would additionally match things like the empty string if the variable name was misspelled.\n \n ### Exceptions:\n \n If your script's logic handles unrecognized flags in another way, e.g. after the `case` statement, you can ignore this warning.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: This pattern always overrides a later one. [SC2221]"},{"from": "gpt", "value": "## This pattern always overrides a later one.\n \n ### Problematic code:\n \n ```sh\n case \"$1\" in\n -?) echo \"Usage: $0 [-n]\";;\n -n) echo \"Hello World\";;\n *) exit 1;;\n esac\n ```\n \n ### Correct code:\n \n ```sh\n case \"$1\" in\n -\\?) echo \"Usage: $0 [-n]\";;\n # '-?') echo \"Usage: $0 [-n]\";; # Also valid\n -n) echo \"Hello World\";;\n *) exit 1;;\n esac\n ```\n ### Rationale:\n \n You have specified multiple patterns in a `case` statement, where one will always override the other. The pattern being overridden is indicated with a [[SC2222]] warning.\n \n In the example, `-?` actually matches a dash followed by any character, such as `-n`. This means that the later `-n` branch will never trigger. In this case, the correct solution is to escape the `-\\?` so that it doesn't match `-n`. \n \n Another common reason for this is accidentally duplicating a branch. In this case, fix or delete the duplicate branch.\n \n ### Exceptions:\n \n None. One could argue that having `-*|--*) echo \"Invalid flag\";` is a readability issue, even though the second pattern follows from the first. In this case, you can either rearrange the pattern from most to least specific, i.e. `--*|-*)` or ignore the error.\n \n When ignoring this error, remember that ShellCheck directives have to go in front of the `case` statement, and not in front of the branch:\n \n # shellcheck disable=SC2221,SC2222\n case \"$1\" in\n -n) ...;;\n # no directive here\n -*|--*) echo \"Unknown flag\" ;;\n esac\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: This pattern never matches because of a previous pattern. [SC2222]"},{"from": "gpt", "value": "## This pattern never matches because of a previous pattern.\n \n See companion warning [[SC2221]].\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: This default assignment may cause DoS due to globbing. Quote it. [SC2223]"},{"from": "gpt", "value": "## This default assignment may cause DoS due to globbing. Quote it.\n \n ### Problematic code:\n \n ```sh\n : ${COLUMNS:=80}\n ```\n \n ### Correct code:\n \n ```sh\n : \"${COLUMNS:=80}\"\n ```\n ### Rationale:\n \n This statement is an idiomatic way of assigning a default value to an environment variable. However, even though it's passed to `:` which ignores arguments, it's better to quote it.\n \n If `COLUMNS='/*/*/*/*/*/*'`, the unquoted, problematic code may spend 30+ minutes trashing the disk as it unnecessarily tries to glob expand the value. \n \n The correct code uses double quotes to avoid glob expansion, and therefore does not have this problem.\n \n When quoting, make sure to update any inner quotes:\n \n : ${var:='foo'} # Assigns foo without quotes\n : \"${var:='foo'}\" # Assigns 'foo' with quotes\n \n \n ### Exceptions:\n \n None, though this issue is largely theoretical.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: This `mv` has no destination. Check the arguments. [SC2224]"},{"from": "gpt", "value": "## This `mv` has no destination. Check the arguments.\n \n ### Problematic code:\n \n ```sh\n mv \"$file $dir\"\n ```\n \n ### Correct code:\n \n ```sh\n mv \"$file\" \"$dir\"\n ```\n ### Rationale:\n \n ShellCheck found an `mv` command with a single parameter. This may be because the source and destination was accidentally merged into a single argument, or because the line was broken in an invalid way.\n \n Fix the `mv` statement by correctly specifying both source and destination.\n \n ### Exceptions:\n \n None\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: This `cp` has no destination. Check the arguments. [SC2225]"},{"from": "gpt", "value": "## This `cp` has no destination. Check the arguments.\n \n ### Problematic code:\n \n ```sh\n cp \"$file $dir\"\n ```\n \n ### Correct code:\n \n ```sh\n cp \"$file\" \"$dir\"\n ```\n ### Rationale:\n \n ShellCheck found a `cp` command with a single parameter. This may be because the source and destination was accidentally merged into a single argument, or because the line was broken in an invalid way.\n \n Fix the `cp` statement by correctly specifying both source and destination.\n \n ### Exceptions:\n \n None\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: This `ln` has no destination. Check the arguments, or specify `.` explicitly. [SC2226]"},{"from": "gpt", "value": "## This `ln` has no destination. Check the arguments, or specify `.` explicitly.\n \n ### Problematic code:\n \n ```sh\n ln \"$file $dir\"\n ```\n \n or\n \n ```sh\n ln /foo/bar/baz\n ```\n \n ### Correct code:\n \n ```sh\n ln \"$file\" \"$dir\"\n ```\n \n or\n \n ```sh\n ln /foo/bar/baz .\n ```\n ### Rationale:\n \n ShellCheck found a `ln` command with a single parameter. This may be because the source and destination was accidentally merged into a single argument, because the line was broken in an invalid way, or because you're using a non-standard invocation of `ln` that defaults to linking the argument into the current directory.\n \n If you wanted to specify both source and destination, fix the `ln` statement.\n \n If you wanted to link a file into the current directory, prefer using the more explicit and POSIX standard invocation `ln /your/file .` \n \n ### Exceptions:\n \n None.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Redirection applies to the find command itself. Rewrite to work per action (or move to end). [SC2227]"},{"from": "gpt", "value": "## Redirection applies to the find command itself. Rewrite to work per action (or move to end).\n \n ### Problematic code:\n \n ```sh\n find . -name '*.ppm' -exec pnmtopng {} > {}.png \\;\n ```\n \n ### Correct code:\n \n ```sh\n find . -name '*.ppm' -exec sh -c 'pnmtopng \"$1\" > \"$1.png\"' _ {} \\;\n ```\n ### Rationale:\n \n ShellCheck detected a `find` command with a redirection in the middle.\n \n This redirection may have been intended to apply only to a specific action like `-exec` or `-print`, but it does in fact apply to the entire `find` command:\n \n # This command\n find . -name '*.ppm' -exec pnmtopng {} > {}.png \\;\n \n # Is the same as this\n {\n find . -name '*.ppm' -exec pnmtopng {} \\;\n } > {}.png \n \n To perform a redirection per action, rewrite it with e.g. `-exec sh -c '...' _ {} \\;` \n \n \n ### Exceptions:\n \n If the redirection is something like `> /dev/null` where you don't mind it applying to the whole `find` and not individual results, you can move the redirection to the end of command to make it clear to ShellCheck (and humans) that it's not meant per command:\n \n find . -exec foo {} > /dev/null \\; # Ambiguous syntax. Is it per -exec or not?\n find . -exec foo {} \\; > /dev/null # Identical command with clear intent.\n \n There is no difference in behavior between the two.\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: This does not read `foo`. Remove `$`/`${}` for that, or use `${var?}` to quiet. [SC2229]"},{"from": "gpt", "value": "## This does not read `foo`. Remove `$`/`${}` for that, or use `${var?}` to quiet.\n \n ### Problematic code:\n \n ```sh\n read $foo\n ```\n \n ### Correct code:\n \n ```sh\n read foo\n ```\n \n ### Rationale:\n \n `read` takes a variable name, but shellcheck has noticed that you give it an expanded variable instead. This will populate whatever the variable expans to instead of the variable itself. For example:\n \n foo=bar\n read $foo # Reads data into 'bar', not into 'foo'\n read foo # Reads data into 'foo'\n \n ### Exceptions:\n \n If this is intentional and you do want to read a variable through an indirect reference, you can silence this warning with a directive:\n \n ```sh\n # shellcheck disable=SC2229\n read \"$foo\"\n ```\n \n Or take advantage of the fact that ShellCheck only warns when no parameter expansion modifiers are applied:\n \n ```sh\n read \"${foo}\" # ShellCheck warns\n read \"${foo?}\" # No warning\n ```\n \n `${foo?}` fails when `foo` is unset, which is fine since `read` would have failed too. The main side effect is an improved runtime error message in that case.\n \n ### Related resources:\n \n * [Bash Pitfalls #12](https://mywiki.wooledge.org/BashPitfalls#pf12): `read $foo`\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: `which` is non-standard. Use builtin `command -v` instead. [SC2230]"},{"from": "gpt", "value": "## `which` is non-standard. Use builtin `command -v` instead.\n \n This is an [[optional]] suggestion. It must be explicitly enabled with a [[directive]] `enable=deprecate-which` in a `# shellcheck` comment or `.shellcheckrc`\n \n ### Problematic code:\n \n ```sh\n which grep\n ```\n \n ### Correct code:\n \n ```sh\n # For the path of a single, unaliased, external command,\n # or to check whether this will just \"run\" in this shell:\n command -v grep\n # To check whether commands exist, without obtaining a reusable path:\n hash grep\n ```\n \n ### Rationale:\n \n `which` is a non-standard, external tool that locates an executable in PATH. `command -v` is a POSIX standard builtin, which uses the same lookup mechanism that the shell itself would.\n \n ### Exceptions:\n \n This check is opt-in only in 0.7.1+, and you may choose to [[ignore]] it in earlier versions. `which` is very common, and some prefer its executable-or-nothing behavior over `command -v`'s handling of builtins, functions and aliases.\n \n ### Caveats:\n \n #### `command -v` does not check ALL parameters\n \n `command -v` succeeds (with exit code 0) if *any* command exists:\n \n ```\n # grep is in /usr/bin/grep\n # foobar is not in path\n #\n $ command -v -- grep foobar; echo $?\n 0\n ```\n \n In the above example, it should have failed and exited with 1 unless *all* commands\n exist, if it were to be a replacement for `which`. Other problems associated with\n `command` include its inclusion of builtins, aliases, and functions.\n \n An alternative is:\n \n ```\n $ hash \n ```\n \n Which observes the standard behaviour of failures.\n \n To obtain a path, `type -p` can be used instead. Like `command -v`, it has a similarly\n quirky behavior with builtins, aliases, and functions, although this is\n arguably milder since it would print nothing for these cases. The failure condition is\n similar to `hash`.\n \n ### Related resources:\n \n * `shellcheck` issue: [#1162 command -v is not a direct replacement for which](https://github.com/koalaman/shellcheck/issues/1162) (Discussion)\n * [Check if a program exists from a Bash script](https://stackoverflow.com/a/677212/1899640) on StackOverflow.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Quote expansions in this `for` loop glob to prevent word splitting, e.g. `\"${dir}\"/*.txt`. [SC2231]"},{"from": "gpt", "value": "## Quote expansions in this `for` loop glob to prevent word splitting, e.g. `\"${dir}\"/*.txt`.\n \n ### Problematic code:\n \n ```sh\n for file in ${dir}/*.txt\n do\n echo \"Found ${file}\"\n done\n ```\n \n ### Correct code:\n \n ```sh\n for file in \"${dir}\"/*.txt\n do\n echo \"Found ${file}\"\n done\n ```\n \n ### Rationale:\n \n When iterating over globs containing expansions, you can still quote all expansions in the path to better handle whitespace and special characters.\n \n Just make sure glob characters are outside quotes. `\"${dir}/*.txt\"` will not glob expand, but `\"${dir}\"/*.txt` or `\"${dir}\"/*.\"${ext}\"` will. \n \n ### Exceptions:\n \n Exceptions similar to [[SC2086]] apply. If the variable is expected to contain globs, such as if `dir=\"tmp/**\"` in the example, you can ignore this message.\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Can't use `sudo` with builtins like `cd`. Did you want `sudo sh -c ..` instead? [SC2232]"},{"from": "gpt", "value": "## Can't use `sudo` with builtins like `cd`. Did you want `sudo sh -c ..` instead?\n \n ### Problematic code:\n \n ```sh\n sudo cd /root\n pwd\n ```\n \n ### Correct code:\n \n ```sh\n sudo sh -c 'cd /root && pwd'\n ```\n ### Rationale:\n \n Due to the Unix process model, `sudo` can only change the privileges of a new, external process. It can not grant privileges to a currently running process.\n \n This means that shell builtins -- commands that are interpreted by the current shell rather than through program invocation -- cannot be run with `sudo`. This includes `cd`, `source`, `read`, and others.\n \n Instead you can run a shell with `sudo`, and have that shell run the builtins you want. Just be aware that what happens in that shell stays in that shell:\n \n sudo sh -c 'cd /root && pwd' # This shows /root\n pwd # This shows the original directory\n \n ### Exceptions:\n \n None.\n \n ### Related resources:\n \n * [SuperUser](https://superuser.com/questions/241129/why-wont-sudo-cd-work): Why won't “sudo cd” work?\n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Remove superfluous `(..)` around condition to avoid subshell overhead. [SC2233]"},{"from": "gpt", "value": "## Remove superfluous `(..)` around condition to avoid subshell overhead.\n \n ### Problematic code:\n \n ```sh\n if ([ \"$x\" -gt 0 ])\n then true; fi\n ```\n \n ### Correct code:\n \n ```sh\n if [ \"$x\" -gt 0 ]\n then true; fi\n ```\n \n ### Rationale:\n \n The shell syntax is `if cmd`, `elif cmd`, `while cmd` and `until cmd` without any parentheses. Instead, parentheses are an independent construct used to create subshells.\n \n ShellCheck has noticed that you're wrapping `(..)` around one or more test commands. This is unnecessary, and the resulting fork adds quite a lot of overhead:\n \n ```\n $ i=0; time while ( [ \"$i\" -lt 10000 ] ); do i=$((i+1)); done\n real 0m6.998s\n user 0m3.453s\n sys 0m3.464s\n \n $ i=0; time while [ \"$i\" -lt 10000 ]; do i=$((i+1)); done\n real 0m0.055s\n user 0m0.054s\n sys 0m0.001s\n ```\n \n Just delete the surrounding `(..)` since they serve no purpose and only slows the script down.\n \n ### Exceptions:\n \n This issue only affects performance, not correctness, so it can be safely [[ignore]]d.\n \n If you are considering doing it to stylistically match C-like languages, please note that this is not conventional and that you'd probably recommend someone use `if (1 == 2)` over `if (system(\"[ 1 = 2 ]\"))` in C no matter which language they're used to.\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Remove superfluous `(..)` around test command to avoid subshell overhead. [SC2234]"},{"from": "gpt", "value": "## Remove superfluous `(..)` around test command to avoid subshell overhead.\n \n ### Problematic code:\n \n ```sh\n ([ \"$x\" -gt 0 ]) && foo\n ```\n \n ### Correct code:\n \n ```sh\n [ \"$x\" -gt 0 ] && foo\n ```\n \n ### Rationale:\n \n You are wrapping a single test command in `(..)`, creating an unnecessary subshell. This serves no purpose, but is significantly slower:\n \n ```\n $ i=0; time while ( [ \"$i\" -lt 10000 ] ); do i=$((i+1)); done\n real 0m6.998s\n user 0m3.453s\n sys 0m3.464s\n \n $ i=0; time while [ \"$i\" -lt 10000 ]; do i=$((i+1)); done\n real 0m0.055s\n user 0m0.054s\n sys 0m0.001s\n ```\n \n Just delete the surrounding `(..)` since they serve no purpose and only slows the script down.\n \n ### Exceptions:\n \n This issue only affects performance, not correctness, and can be [[ignore]]d for stylistic reasons.\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Use `{ ..; }` instead of `(..)` to avoid subshell overhead. [SC2235]"},{"from": "gpt", "value": "## Use `{ ..; }` instead of `(..)` to avoid subshell overhead.\n \n ### Problematic code:\n \n ```sh\n ([ \"$x\" ] || [ \"$y\" ]) && [ \"$z\" ]\n ```\n \n ### Correct code:\n \n ```sh\n { [ \"$x\" ] || [ \"$y\" ]; } && [ \"$z\" ]\n ```\n \n ### Rationale:\n \n You appear to be using `(..)` to group test commands. This creates a subshell, making it unnecessarily slow. Avoid this by using `{ ..; }` to group.\n \n Be careful to note that unlike `(..)`, this requires both a space after the `{` and a semicolon before the `}`.\n \n For example, `(cmd)`, `(cmd;)` and `( cmd )` are all valid, but `{cmd}`, `{cmd;}` and `{ cmd }` are all syntax errors because they lack either or both of the spaces and semicolon. The correct form is `{ cmd; }`\n \n Here's a small benchmark showing that the subshell version is more than 100x slower:\n \n ```\n $ i=0; time for i in {1..10000}; do ([ \"$x\" ] || [ \"$y\" ]) && [ \"$z\" ]; done\n real 0m7.122s\n user 0m4.204s\n sys 0m2.825s\n \n $ i=0; time for i in {1..10000}; do { [ \"$x\" ] || [ \"$y\" ]; } && [ \"$z\" ]; done\n real 0m0.055s\n user 0m0.055s\n sys 0m0.000s\n ```\n \n \n \n ### Exceptions:\n \n None.\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Use `-n` instead of `! -z`. [SC2236]"},{"from": "gpt", "value": "## Use `-n` instead of `! -z`.\n \n (or \"Use `-z` instead of `! -n`\")\n \n ### Problematic code:\n \n ```sh\n if [ ! -n \"$JAVA_HOME\" ]; then echo \"JAVA_HOME not specified\"; fi\n if [ ! -z \"$STY\" ]; then echo \"You are already running screen\"; fi\n ```\n \n ### Correct code:\n \n ```sh\n if [ -z \"$JAVA_HOME\" ]; then echo \"JAVA_HOME not specified\"; fi\n if [ -n \"$STY\" ]; then echo \"You are already running screen\"; fi\n ```\n \n ### Rationale:\n \n You have negated `test -z` or `test -n`, resulting in a needless double-negative. You can just use the other operator instead:\n \n # Identical tests to verify that a value is assigned\n [ ! -z foo ] # Not has no value\n [ -n foo ] # Has value\n \n # Identical tests to verify that a value is empty\n [ ! -n foo ] # Not is non-empty\n [ -z foo ] # Is empty\n \n ### Exceptions:\n \n This is a stylistic issue that does not affect correctness. If you prefer the original expression, you can [[Ignore]] it with a directive or flag.\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n * [Bash reference manual for -z and -n](https://www.gnu.org/software/bash/manual/html_node/Bash-Conditional-Expressions.html#Bash-Conditional-Expressions).\n * Note: Be careful with quoting variables (which you should always do anyway): `[ ! -z $var ]` might work, but `[ -n $var]` will not. `[ -n \"$var\" ]` will do what you expect. \n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Use `[ -n .. ]` instead of `! [ -z .. ]`. [SC2237]"},{"from": "gpt", "value": "## Use `[ -n .. ]` instead of `! [ -z .. ]`.\n \n (or \"Use `[ -z .. ]` instead of `! [ -n .. ]`.)\n \n ### Problematic code:\n \n ```sh\n if ! [ -n \"$JAVA_HOME\" ]; then echo \"JAVA_HOME not specified\"; fi\n if ! [ -z \"$STY\" ]; then echo \"You are already running screen\"; fi\n ```\n \n ### Correct code:\n \n ```sh\n if [ -z \"$JAVA_HOME\" ]; then echo \"JAVA_HOME not specified\"; fi\n if [ -n \"$STY\" ]; then echo \"You are already running screen\"; fi\n ```\n \n ### Rationale:\n \n You have negated `test -z` or `test -n`, resulting in a needless double-negative. You can just use the other operator instead:\n \n # Identical tests to verify that a value is assigned\n ! [ -z foo ] # Not has no value\n [ -n foo ] # Has value\n \n # Identical tests to verify that a value is empty\n ! [ -n foo ] # Not is non-empty\n [ -z foo ] # Is empty\n \n ### Exceptions:\n \n This is a stylistic issue that does not affect correctness. If you prefer the original expression, you can't not [[Ignore]] it with a directive or flag.\n \n ### Related resources:\n \n * [Google Bash Style Guide][google-bash] on Testing Strings\n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n \n [google-bash]: https://google.github.io/styleguide/shell.xml?showone=Testing_Strings#Testing_Strings\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Redirecting to/from command name instead of file. Did you want pipes/xargs (or quote to ignore)? [SC2238]"},{"from": "gpt", "value": "## Redirecting to/from command name instead of file. Did you want pipes/xargs (or quote to ignore)?\n \n ### Problematic code:\n \n ```sh\n cat file > tr -d '\\r'\n cat file > rm\n ```\n \n ### Correct code:\n \n ```sh\n cat file | tr -d '\\r' # tr reads stdin\n cat file | xargs -d '\\n' rm # rm reads arguments\n ```\n \n ### Rationale:\n \n You are using file redirection, but the filename is an unquoted command name. Instead of running the command and feeding data to it, this just writes to a file with the same name. \n \n To run the command and feed data to it, determine how it gets its data:\n \n * If the command reads from STDIN, simply use a pipe as in the first example.\n * If the command reads multiple arguments, use a pipe to `xargs` as in the second example\n \n Note that `xargs` has many pitfalls when it comes to spaces and quotes. `cat file | xargs rm` will appear to work during testing, but fails for filenames like `My File.txt` or `Can't_Fight_This_Feeling.mp3`. The example uses the GNU extension `-d '\\n'` to more safely handle these names. \n \n ### Exceptions:\n \n If you actually did want to write a file named after a command, simply quote the filename to let ShellCheck know you meant it literally and not as a command name. This does not change anything about how the script works:\n \n ```sh\n # Write to a file literally named 'rm', does not try to delete anything\n echo \"A potentially dangerous command\" > \"rm\" \n ```\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Ensure the shebang uses the absolute path to the interpreter. [SC2239]"},{"from": "gpt", "value": "## Ensure the shebang uses the absolute path to the interpreter.\n \n ### Problematic code:\n \n ```sh\n #!bin/sh\n echo \"Hello World\"\n ```\n \n ### Correct code:\n \n ```sh\n #!/bin/sh\n echo \"Hello World\"\n ```\n \n ### Rationale:\n \n The script's interpreter, as specified in the shebang, does not start with a `/`.\n \n The interpreter should always be specified by absolute path to ensure that the script can be executed from any directory. When it's not, it's generally a typo like in the problematic example.\n \n If you don't know where the interpreter is and you hoped to use `#! bash`, this is not an option. Use `/usr/bin/env` instead:\n \n ```sh\n #!/usr/bin/env bash\n echo \"Hello World\"\n ``` \n \n While not required by POSIX, `env` can essentially always be found in `/usr/bin` and will search the PATH for the specified executable.\n \n ### Exceptions:\n \n None.\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: The dot command does not support arguments in sh/dash. Set them as variables. [SC2240]"},{"from": "gpt", "value": "## The dot command does not support arguments in sh/dash. Set them as variables.\n \n ### Problematic code:\n \n ```sh\n #!/bin/sh\n . include/myscript example.com 80\n ```\n \n ### Correct code:\n \n ```sh\n #!/bin/sh\n host=example.com port=80 . include/myscript \n ```\n ### Rationale:\n \n In Bash and Ksh, you can use `. myscript arg1 arg2..` to set `$1` and `$2` in the sourced script.\n \n This is not the case in Dash, where any additional arguments are ignored, or in POSIX sh where the behavior is unspecified.\n \n Instead, assign arguments to variables and rewrite the sourced script to read from them.\n \n ### Exceptions:\n \n None.\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: The exit status can only be one integer 0-255. Use stdout for other data. [SC2241]"},{"from": "gpt", "value": "## The exit status can only be one integer 0-255. Use stdout for other data.\n \n ### Problematic code:\n \n ```sh\n exit foo bar\n ```\n \n ### Correct code:\n \n ```sh\n echo foo\n echo bar\n exit\n ```\n \n ### Rationale:\n \n In bash, `exit` can only be used to signal success or failure (0 = success, 1-255 = failure).\n \n To exit with textual or multiple values from a function, write them to stdout and capture them with command substitution instead.\n \n See [[SC2242]] for more information.\n \n ### Exceptions:\n \n None\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Can only exit with status 0-255. Other data should be written to stdout/stderr. [SC2242]"},{"from": "gpt", "value": "## Can only exit with status 0-255. Other data should be written to stdout/stderr.\n \n ### Problematic code:\n \n ```sh\n exit \"Bad filename\"\n ```\n \n ### Correct code:\n \n ```sh\n echo \"Bad filename\" >&2\n exit 1\n ```\n \n ### Rationale:\n \n `exit` can only be used to signal success or failure (0 = success, 1-255 = failure). It can not be used to return string data, and it can not be used to print error messages.\n \n String data should be written stdout, before an `exit 0` to exit with success.\n \n Errors should instead be written to stderr, with an `exit 1` (or higher) to exit with failure:\n \n ```\n if [ ! -f \"$1\" ]\n then\n echo \"$1 is not a regular file\" >&2\n exit 1\n fi\n ```\n \n Note in particular that `exit -1` is equivalent to `exit 255`, but that `exit 1` is the more canonical way of expressing the first possible error code.\n \n ### Exceptions:\n \n None\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Prefer explicit `-n` to check for output (or run command without `[`/`[[` to check for success) [SC2243]"},{"from": "gpt", "value": "## Prefer explicit `-n` to check for output (or run command without `[`/`[[` to check for success)\n \n ### Problematic code:\n \n ```sh\n if [ \"$(mycommand --myflags)\" ]\n then\n echo \"True\"\n fi\n ```\n \n ### Correct code:\n \n ```sh\n # Check that the command outputs something on stdout\n if [ -n \"$(mycommand --myflags)\" ]\n then\n echo \"The command had output on stdout\"\n fi\n \n # Check instead that the command succeeded (exit code = 0)\n if mycommand --myflags\n then\n echo \"The command reported success\"\n fi\n ```\n \n (if the command instead outputs \"0\" or \"false\", see [[SC2244]] for integer and \"boolean\" comparisons)\n \n ### Rationale:\n \n `[ \"$(mycommand)\" ]` is equivalent to `[ -n \"$(mycommand)\" ]` and checks whether the command's output on stdout was non-empty.\n \n Users more familiar with other languages are often surprised to learn that it is nothing like e.g. `if (myfunction())`, since it does not care about what the command/function `return`s.\n \n Using an explicit `-n` helps clarify that this is purely a string operation. And of course, if the intention was to check whether the command ran successfully, now would be a good time to fix it as in the alternate example.\n \n ### Exceptions:\n \n If you are familiar with the semantics of `[`, you can [[ignore]] this suggestion with no ill effects.\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Prefer explicit `-n` to check non-empty string (or use `=`/`-ne` to check boolean/integer). [SC2244]"},{"from": "gpt", "value": "## Prefer explicit `-n` to check non-empty string (or use `=`/`-ne` to check boolean/integer).\n \n ### Problematic code:\n \n ```sh\n if [ \"$1\" ]\n then\n echo \"True\"\n fi\n ```\n \n ### Correct code:\n \n ```sh\n # Check if $1 is empty or non-empty\n if [ -n \"$1\" ]\n then\n echo \"True, $1 is a non-empty value\"\n fi\n \n # Check instead if $1 is true or false, as in Java\n [ \"$1\" = \"true\" ]\n \n # Check instead if $1 is non-zero or zero, as in C\n [ \"$1\" -ne 0 ]\n \n # Check instead if $1 is defined (even if just assigned the empty string) or undefined\n [ \"${1+x}\" = \"x\" ]\n \n ```\n \n ### Rationale:\n \n `[ \"$var\" ]` is equivalent to `[ -n \"$var\" ]` and checks that a string is non-empty.\n \n Users more familiar with other languages are often surprised to learn that `[ \"$var\" ]` is true when:\n \n * `var=false`\n * `var=0`\n * `var=null`\n * `var=\" \"`\n \n Adding the explicit `-n` helps clarify that this is a string comparison, and not related to any concept of boolean values or \"truthiness\" as it is in most languages.\n \n ### Exceptions:\n \n If you are familiar with the semantics of `[`, you can [[ignore]] this stylistic suggestion with no ill effects.\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: -d only applies to the first expansion of this glob. Use a loop to check any/all. [SC2245]"},{"from": "gpt", "value": "## -d only applies to the first expansion of this glob. Use a loop to check any/all.\n \n ### Problematic code:\n \n ```sh\n #!/bin/ksh\n \n if [ -f ksh* ]\n then\n echo \"The file exists\"\n fi\n ```\n \n ### Correct code:\n \n ```sh\n #!/bin/ksh\n \n for f in ksh*\n do\n if [ -f \"$f\" ]\n then\n echo \"Found a matching file: $f\"\n fi\n done\n ```\n ### Rationale:\n \n Ksh has the curious behavior of ignoring anything after an unrecognized flag to `test`/`[`, which means that file checking operators against globs will effectively apply the operator to the first expansion:\n \n ```sh\n [ -f ksh* ] # This\n [ -f ksh93u ksh93u.tar ksh93u.tar.gz ] # Becomes this\n [ -f ksh93u ] # And is interpreted like this\n ```\n \n This is an issue when you have multiple matches for a glob. Instead of checking some or all, it only checks the first result and ignores the rest. To ensure that all results are considered (either to check that *any* or *all* results match the operator), use a loop explicitly.\n \n If you really only want to match the first result of the glob expansion as sorted alphabetically in the current locale, you can make this intention explicit:\n \n matches=( ksh* )\n if [ -f \"${matches[0]}\" ]\n then\n echo \"The first result is a file\"\n fi\n \n ### Exceptions:\n \n If you only care that entries exists, use `-e`. ShellCheck does not warn in this case, since all files resulting from glob expansion necessarily exist.\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: This shebang specifies a directory. Ensure the interpreter is a file. [SC2246]"},{"from": "gpt", "value": "## This shebang specifies a directory. Ensure the interpreter is a file.\n \n ### Problematic code:\n \n ```sh\n #!/bin/sh/\n echo \"Hello World\"\n ```\n \n ### Correct code:\n \n ```sh\n #!/bin/sh\n echo \"Hello World\"\n ```\n ### Rationale:\n \n The shebang specifies which file to use as an interpreter, but probably due to some kind of typo, your script's interpreter ends in a `/`, indicating a directory.\n \n Ensure it points to a valid executable filename.\n \n ### Exceptions:\n \n None\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Flip leading `$` and `\"` if this should be a quoted substitution. [SC2247]"},{"from": "gpt", "value": "## Flip leading `$` and `\"` if this should be a quoted substitution.\n \n ### Problematic code:\n \n ```sh\n var=$\"(whoami)\"\n ```\n \n ### Correct code:\n \n ```sh\n var=\"$(whoami)\"\n ```\n \n ### Rationale:\n \n ShellCheck has found a `$\"(` or `$\"{` . This is most likely due to flipping the dollar-sign and double quote:\n \n echo $\"(cmd)\" # Supposed to be \"$(cmd)\"\n echo $\"{var}\" # Supposed to be \"${var}\"\n \n Instead of quoted substitutions, these will be interpreted as localized string resources (`$\"..\"`) containing literal parentheses or curly braces. If this was not intentional, you should flip the `\"` and `$` like in the example.\n \n ### Exceptions:\n \n If you intentionally wanted a localized string literal `$\"..\"` that starts with `(` or `{`, either [[ignore]] this error or start it with a different character.\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Prefer double quoting even when variables don't contain special characters. [SC2248]"},{"from": "gpt", "value": "# Prefer double quoting even when variables don't contain special characters.\n \n This is an [[optional]] suggestion. It must be explicitly enabled with a [[directive]] `enable=quote-safe-variables` in a `# shellcheck` comment or `.shellcheckrc`\n \n ## Problematic code:\n \n ```shell\n subdir='example'\n \n cd ${subdir}\n ```\n \n ## Correct code:\n \n ```shell\n subdir='example'\n \n cd \"${subdir}\"\n ```\n \n ## Rationale:\n \n Shellcheck normally warns about unquoted variable use due to potential globbing or word splitting issues. See [[SC2086]] for details. However if it is determined that a variable does not have have spaces or special characters it will omit that warning. This optional warning exists to suggest that quotes be used even in this scenario. If the code is later changed such that special characters can appear in the variable, having its use already quoted will prevent issues.\n \n This optional warning is also helpful if shellcheck's analysis of the variable contents is wrong because of indirect modification of the variable or because unknown commands implemented as shell functions have modified the variable. \n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Consider adding a default `*)` case, even if it just exits with error. [SC2249]"},{"from": "gpt", "value": "## Consider adding a default `*)` case, even if it just exits with error.\n \n ### Problematic code:\n \n ```sh\n case \"$1\" in\n start) start_service ;;\n stop) stop_service ;;\n restart|reload|force-reload)\n stop_service;\n start_service;;\n esac\n ```\n \n ### Correct code:\n \n ```sh\n case \"$1\" in\n start) start_service ;;\n stop) stop_service ;;\n restart|reload|force-reload)\n stop_service;\n start_service;;\n *)\n echo >&2 \"Invalid choice: $1\"\n exit 1\n esac\n ```\n \n ### Rationale:\n \n ShellCheck found a `case` statement that may not be considering all possible cases. This may mean that only the [happy paths](https://en.wikipedia.org/wiki/Happy_path) are accounted for.\n \n Consider adding a default case to handle other values. If you don't know what to do or don't believe it'll ever happen, exiting with an error is good, fail-fast practice.\n \n The example is adapted from a real world Debian init script, which due to a missing default case reports success on any misspelled command (here with underscore instead of dash):\n \n ```\n $ /etc/init.d/screen-cleanup force_reload && echo success\n success\n ```\n \n ### Exceptions:\n \n This suggestion only triggers in verbose mode (`-S verbose`). \n \n If you don't have a default case because the default should be to take no action, consider adding a comment to other humans:\n \n ```\n case \"$(uname)\" in\n CYGWIN*) cygwin=1;;\n MINGW*) mingw=1;;\n *) ;; # No special workarounds identified\n esac\n ```\n \n If you believe that it's impossible for the expression to have any other value, it's considered good practice to add the equivalent of an `assert(0)` to fail fast if this assumption should turn out to be incorrect in the current or future versions:\n \n ```\n case \"$result\" in\n true) proceed;;\n false) cancel;;\n *) echo >&2 \"Submit bug report: '$result' should be true or false.\"\n exit 127\n esac\n ```\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Prefer putting braces around variable references even when not strictly required. [SC2250]"},{"from": "gpt", "value": "## Prefer putting braces around variable references even when not strictly required.\n \n This is an [[optional]] suggestion. It must be explicitly enabled with a [[directive]] `enable=require-variable-braces` in a `# shellcheck` comment or `.shellcheckrc`\n \n ## Problematic code:\n \n ```shell\n partial_path='example'\n \n curl \"http://example.com/$partial_path_version/explain.html\"\n ```\n \n ## Correct code:\n \n ```shell\n partial_path='example'\n \n curl \"http://example.com/${partial_path}_version/explain.html\"\n ```\n \n ## Rationale:\n \n If a variable gets called, and there is a string that gets appended to the variable that could get misinterpreted as possibly part of the name of the variable. Then it will not call the right variable.\n \n ## Related resources:\n - [StackOverflow: How do we separate variables from letters in shell scripting](https://stackoverflow.com/questions/18320133/how-do-we-separate-variables-from-letters-in-shell-scripting)\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: This `!` is not on a condition and skips errexit. Add `|| exit 1` or make sure `$?` is checked. [SC2251]"},{"from": "gpt", "value": "## This `!` is not on a condition and skips errexit. Add `|| exit 1` or make sure `$?` is checked.\n \n ### Problematic code:\n \n ```sh\n set -e\n ! false\n rest\n ```\n \n ### Correct code:\n \n ```sh\n set -e\n ! false || exit 1\n ```\n \n ### Rationale:\n \n ShellCheck has found a command inverted with `!` that may have no effect. In particular, it does not appear as a condition in an `if` statement or `while` loop, or as the final command in a script or function.\n \n The most common reason for this is thinking that it'll trigger `set -e` aka `errexit` if a command succeeds, as in the example. This is not the case: `!` will inhibit errexit both on success and failure of the inverted command.\n \n Adding `|| exit ` will instead exit with failure when the command succeeds.\n \n ### Exceptions:\n \n ShellCheck will not detect cases where `$?` is implicitly or explicitly used to check the value afterwards:\n \n ```\n set -e;\n check_success() { [ $? -eq 0 ] || exit 1; }\n ! false; check_success\n ! true; check_success\n ```\n \n In this case, you can [[ignore]] the warning.\n \n ### Related resources:\n \n * StackOverflow: [Why do I need parenthesis In bash `set -e` and negated return code](https://stackoverflow.com/questions/39581150/why-do-i-need-parenthesis-in-bash-set-e-and-negated-return-code/39582012)\n * [The \"Use && exit 1\" for SC2251 can result in a wrong exit code](https://github.com/koalaman/shellcheck/issues/3121)\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: You probably wanted `&&` here, otherwise it's always true. [SC2252]"},{"from": "gpt", "value": "## You probably wanted `&&` here, otherwise it's always true.\n \n ### Problematic code:\n \n ```sh\n if [ \"$1\" != foo ] || [ \"$1\" != bar ]\n then\n echo \"$1 is not foo or bar\"\n fi\n ```\n \n ### Correct code:\n \n ```sh\n if [ \"$1\" != foo ] && [ \"$1\" != bar ]\n then\n echo \"$1 is not foo or bar\"\n fi\n ```\n \n ### Rationale:\n \n This is not a bash issue, but a simple, common logical mistake applicable to all languages. \n \n `[ \"$1\" != foo ] || [ \"$1\" != bar ]` is always true (when `foo != bar`):\n \n * If `$1 = foo` then `$1 != bar` is true, so the statement is true.\n * If `$1 = bar` then `$1 != foo` is true, so the statement is true.\n * If `$1 = cow` then `$1 != foo` is true, so the statement is true.\n \n `[ $1 != foo ] && [ $1 != bar ]` matches when `$1` is neither `foo` nor `bar`:\n \n * If `$1 = foo`, then `$1 != foo` is false, so the statement is false.\n * If `$1 = bar`, then `$1 != bar` is false, so the statement is false.\n * If `$1 = cow`, then both `$1 != foo` and `$1 != bar` is true, so the statement is true.\n \n This statement is identical to `! [ \"$1\" = foo ] || [ \"$1\" = bar ]`, which also works correctly (by [De Morgan's law](https://en.wikipedia.org/wiki/De_Morgan%27s_laws))\n \n This warning is equivalent to [[SC2055]] and [[SC2056]], which trigger for intra-`test` expressions and arithmetic contexts respectively.\n \n ### Exceptions\n \n Rare.\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Use `-R` to recurse, or explicitly `a-r` to remove read permissions. [SC2253]"},{"from": "gpt", "value": "## Use `-R` to recurse, or explicitly `a-r` to remove read permissions.\n \n ### Problematic code:\n \n ```sh\n chmod -r 0700 dir\n chmod -r file\n ```\n \n ### Correct code:\n \n ```sh\n chmod -R 0700 dir\n chmod a-r file\n ```\n \n ### Rationale:\n \n Many tools use `-r` for recursive operation, but in `chmod` this removes read permissions.\n \n If you wanted to change permissions recursively, change the flag to `-R`. If you wanted to remove read permissions, consider using `a-r` explicitly to make this more obvious.\n \n ### Exceptions:\n \n If you're using it correctly and don't mind the potential for confusion, you can save a single character by ignoring this warning.\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Quote expansions in case patterns to match literally rather than as a glob. [SC2254]"},{"from": "gpt", "value": "## Quote expansions in case patterns to match literally rather than as a glob.\n \n ### Problematic code:\n \n ```sh\n case $input in\n - ) echo \"Reading from stdin...\" ;;\n $output ) echo \"Input should be different from output\" ;;\n esac\n ```\n \n ### Correct code:\n \n ```sh\n case $input in\n - ) echo \"Reading from stdin...\" ;;\n \"$output\" ) echo \"Input should be different from output\" ;;\n esac\n ```\n ### Rationale:\n \n When unquoted variables and command expansions are used in case branch patterns, they will be interpreted as globs. \n \n This can lead to some surprising behavior, such as `case $x in $x) trigger;; esac` not triggering in some cases, such as when `x='Pride and Prejudice [1813].epub'`.\n \n To match the literal content of the variable or expansion, make sure to double quote the expansion.\n \n ### Exceptions:\n \n If you intended to match a dynamically generated pattern, you can ignore this suggestion with a directive.\n \n ### Related resources:\n \n * [[SC2053]], where the same effect can be seen with `[[ $x = $x ]]`.\n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: `[ ]` does not apply arithmetic evaluation. Evaluate with `$((..))` for numbers, or use string comparator for strings. [SC2255]"},{"from": "gpt", "value": "## `[ ]` does not apply arithmetic evaluation. Evaluate with `$((..))` for numbers, or use string comparator for strings.\n \n ### Problematic code:\n \n ```sh\n [ 2*3 -eq array[i] ]\n ```\n \n ### Correct code:\n \n ```sh\n [ $((2*3)) -eq $((array[i])) ]\n ```\n \n ### Rationale:\n \n When using `[[ .. ]]` with numerical comparators (`-eq`, `-lt`, etc), the value on either side will be evaluated as an arithmetic expression. This means that `2*3` will be evaluated to `6`, and `x` will be evaluated to the contents of the variable `$x`.\n \n When using `[ .. ]`, this does not happen. `2*3` and `x` will both be considered invalid numbers. Instead, use e.g. `$((2*3))` to evaluate the expression before passing it to `[ .. ]`.\n \n Alternatively, if the expression should be considered a string, quote the expression and use a string comparison operator like `=` and `!=`. \n \n ### Exceptions:\n \n None\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: This translated string is the name of a variable. Flip leading `$` and `\"` if this should be a quoted substitution. [SC2256]"},{"from": "gpt", "value": "## This translated string is the name of a variable. Flip leading `$` and `\"` if this should be a quoted substitution.\n \n ### Problematic code:\n \n ```sh\n var=\"foo\"\n echo $\"var\"\n ```\n \n ### Correct code:\n \n ```sh\n var=\"foo\"\n echo \"$var\"\n ```\n \n ### Rationale:\n \n `$\"..\"` is a localized string, for example, `echo $\"Hello $USER\"` along with the proper translation files can be used to have the script say \"Bonjour, youruser\" in French locales.\n \n In this case, ShellCheck found a localized string whose contents is also the name of a variable. This could have happened because the user wanted a far more common quoted substitution, e.g. `\"$var\"`, but accidentally switched the leading `$` and `\"`.\n \n ### Exceptions:\n \n If you do want a localized string whose contents is also an active variable, you can [[ignore]] this warning or rename the variable.\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Arithmetic modifications in command redirections may be discarded. Do them separately. [SC2257]"},{"from": "gpt", "value": "## Arithmetic modifications in command redirections may be discarded. Do them separately.\n \n ### Problematic code:\n \n ```sh\n curl \"$URL\" > \"image$((i++)).jpg\"\n ```\n \n ### Correct code:\n \n ```sh\n i=$((i+1))\n curl \"$URL\" > \"image$i.jpg\"\n ```\n ### Rationale:\n \n You are using an arithmetic expression that modifies a variable, e.g. `$((x+=1))` or `$((x++))`, in the name of a file to redirect from/to, in a here document, or in a here string.\n \n The scope of these modifications depends on whether the command itself will fork:\n \n ```sh\n echo foo > $((var++)).txt # Updates in BusyBox and Bash\n cat foo > $((var++)).txt # Updates in Busybox, not in Bash\n gcc foo > $((var++)).txt # Does not update in either\n \n gcc() { /opt/usr/bin/gcc \"$@\"; }\n gcc foo > $((var++)).txt # Now suddenly updates in both\n ```\n \n Rather than rely on knowing which commands do and don't fork, or are and aren't overridden, simply do the updates in a separate command as in the correct code.\n \n ### Exceptions:\n \n If you know your variable is scoped the way you want it, you can ignore this warning.\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n * https://stackoverflow.com/questions/62783161/arithmetic-expression-in-redirection/62964890#62964890\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: The trailing comma is part of the value, not a separator. Delete or quote it. [SC2258]"},{"from": "gpt", "value": "## The trailing comma is part of the value, not a separator. Delete or quote it.\n \n ### Problematic code:\n \n ```sh\n for f in foo, bar, baz\n do\n echo \"$f\"\n done\n ```\n \n ### Correct code:\n \n ```sh\n for f in foo bar baz\n do\n echo \"$f\"\n done\n ```\n \n or\n \n ```sh\n for f in \"foo,\" \"bar,\" \"baz,\"\n do\n echo \"$f\"\n done\n ```\n ### Rationale:\n \n ShellCheck found a `for` loop where the items appear to be separated by commas. These will be treated as literal commas. If the commas are part of the value, enclose them in quotes, or remove them.\n \n ### Exceptions:\n \n None\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: This redirection overrides piped input. To use both, merge or pass filenames. [SC2259]"},{"from": "gpt", "value": "## This redirection overrides piped input. To use both, merge or pass filenames.\n \n ### Problematic code:\n \n ```sh\n gzcat yesterday.log.gz | grep \"$USER\" < today.log\n ```\n \n ### Correct code:\n \n ```sh\n # Specify non-piped inputs as filenames\n gzcat yesterday.log.gz | grep \"$USER\" - today.log\n \n # Or merge multiple inputs into a single stream\n { gzcat yesterday.log.gz; cat today.log; } | grep \"$USER\"\n ```\n \n ### Rationale:\n \n A process only has a single standard input stream. Pipes and input redirections both overwrite it, so you can't use both at the same time. If you try, the redirection takes precedence and the input pipe is closed.\n \n Many commands support specifying multiple filenames, where one can be stdin (canonically by specifying `-` as a filename, or alternatively by using `/dev/stdin`). In these cases, you can rewrite the command to use one piped input, and as many extra files (or process substitutions) as you want.\n \n For commands that only process a single input stream (like `tr`), you can also concatenate multiple commands or files into a single stream using a `{ command group; }` as in the example.\n \n ### Exceptions:\n \n None.\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: This redirection overrides the output pipe. Use `tee` to output to both. [SC2260]"},{"from": "gpt", "value": "## This redirection overrides the output pipe. Use `tee` to output to both.\n \n ### Problematic code:\n \n ```sh\n env > environment.txt | grep '^ANDROID'\n ```\n \n ### Correct code:\n \n ```sh\n env | tee environment.txt | grep '^ANDROID'\n ```\n \n ### Rationale:\n \n A process only has a single standard output stream. Pipes and output redirections both overwrite it, so you can't use both at the same time. If you try, the redirection takes precedence and the output pipe is closed.\n \n If you want to dump output to a file while also piping it, use `tee` as in the example.\n \n ### Exceptions:\n \n None.\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Multiple redirections compete for stdout. Use `cat`, `tee`, or pass filenames instead. [SC2261]"},{"from": "gpt", "value": "## Multiple redirections compete for stdout. Use `cat`, `tee`, or pass filenames instead.\n \n (or `stdin`, or `stderr`, or `FD 3`)\n \n ### Problematic code:\n \n ```sh\n grep foo < input1 < input2 > output1 > output2 > output3\n ```\n \n ### Correct code:\n \n ```sh\n # Merge inputs into a single stream, write outputs individually\n cat input1 input2 | grep foo | tee output1 output2 > output3\n \n # Pass inputs as filenames, write outputs individually\n grep foo input1 input2 | tee output1 output2 > output3\n ```\n ### Rationale:\n \n A file descriptor, whether stdin, stdout, stderr, or non-standard ones, can only point to a single file/pipe.\n \n For input, many commands support processing multiple filenames. In these cases you can just specify the filenames instead of redirecting. Alternatively, you can use `cat` to merge multiple filenames into a single stream.\n \n For output, you can use `tee` to write to multiple output sinks in parallel. \n \n ### Exceptions:\n \n Zsh will automatically `cat` inputs and `tee` outputs, but none of the shells supported by ShellCheck do.\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: This alias can't be defined and used in the same parsing unit. Use a function instead. [SC2262]"},{"from": "gpt", "value": "## This alias can't be defined and used in the same parsing unit. Use a function instead.\n \n ### Problematic code:\n \n ```sh\n function checksum() {\n type md5 && alias md5sum=md5\n md5sum \"$@\" # This calls `md5sum`, not `md5`\n }\n ```\n \n ### Correct code:\n \n ```sh\n function checksum() {\n type md5 && md5sum() { md5 \"$@\"; }\n md5sum \"$@\" # Now this would call `md5` when applicable\n }\n ```\n ### Rationale:\n \n Alias expansion happens at parse time, which means to have an effect, the `alias` command must be executed not just before the alias is invoked, but before the invocation is parsed. \n \n A shell will parse commands until it has a complete set of commands followed by a linefeed. This includes compound commands like `{ brace; groups; }` and `while loops; do true; done`. Here are some examples:\n \n # A single command followed by a linefeed is one unit\n unit 1\n \n # These commands are in the same parsing unit because\n # there is no line feed between them\n unit 2; unit 2;\n \n # These commands are in the same parsing unit because\n # they are part of the same top level brace group\n {\n unit 3\n unit 3\n }\n \n # These commands are in the same parsing unit because\n # there is no linefeed between the groups.\n {\n unit 4\n }; {\n unit 4\n }\n \n Any alias defined in a command in `unit 1` would not take effect until `unit 2` and beyond. Similarly, an alias defined in unit 2 will only take effect in unit 3 and 4.\n \n In the problematic example, the alias is defined and used in a function. Since a function definition is a single compound command, it's considered a single parsing unit. The alias would therefore not have an effect (this is true even if the function is invoked twice, because it's only parsed once).\n \n Does this sound confusing and counter-intuitive? It is. Save yourself the trouble and always use functions instead of aliases.\n \n ### Exceptions:\n \n If the flagged commands are not expected to use the alias, you can ignore this error. ShellCheck may incorrectly flag this if the alias definition and usage were in different branches of an `if` statement.\n \n You can [[ignore]] this warning with a directive. All warnings may always be disabled either before the relevant command or before any outer compound commands, but in this case it's especially useful:\n \n # shellcheck disable=SC2262 # Option A, before compound command\n if true\n then\n # shellcheck disable=SC2262 # Option B, before alias command\n alias foo=bar\n # With either Option A or B, this SC2263 message is auto-suppressed\n foo\n fi\n \n ### Related resources:\n \n * Unix&Linux SE: [bash aliases do not expand even with shopt expand_aliases](https://unix.stackexchange.com/questions/502257/bash-aliases-do-not-expand-even-with-shopt-expand-aliases)\n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Since they're in the same parsing unit, this command will not refer to the previously mentioned alias. [SC2263]"},{"from": "gpt", "value": "## Since they're in the same parsing unit, this command will not refer to the previously mentioned alias.\n See companion warning [[SC2262]]\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: This function unconditionally re-invokes itself. Missing `command`? [SC2264]"},{"from": "gpt", "value": "## This function unconditionally re-invokes itself. Missing `command`?\n \n ### Problematic code:\n \n ```sh\n ls() {\n ls --color=always \"$@\"\n }\n \n cd() {\n cd \"$@\" && ls\n }\n ```\n \n ### Correct code:\n \n Note that `command` is the literal name of a shell builtin. You should not replace it:\n \n ```sh\n ls() {\n command ls --color=always \"$@\"\n }\n \n cd() {\n command cd \"$@\" && ls\n }\n ```\n \n ### Rationale:\n \n ShellCheck found a function that immediately and unconditionally re-invokes itself, causing infinite recursion.\n \n This generally happens when writing a wrapper function with the same name as an existing command, but forgetting to make sure it invokes the existing command and not itself. This is what happened in both of the problematic examples.\n \n To invoke a command when a function by the same name is defined, i.e. to suppress function lookup during execution, use the command confusingly named `command`. For example, to run the system's `ls` instead of the shell function `ls`, use `command ls`.\n \n ### Exceptions:\n \n ShellCheck does not intend to warn about infinite recursion or fork bombs in general. This warning is purely meant for unintentional bugs in well meaning wrapper functions.\n \n If ShellCheck is triggering on an intentionally malicious fork bomb, either [[ignore]] the issue, or simply add a leading command or condition:\n \n :() { true && :|: & }\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Use && for logical AND. Single & will background and return true. [SC2265]"},{"from": "gpt", "value": "## Use && for logical AND. Single & will background and return true.\n \n ### Problematic code:\n \n ```sh\n if [ \"$1\" = \"install\" ] & [ \"$USER\" != \"root\" ]\n then\n echo \"Must be root to install\"\n fi\n ```\n \n ### Correct code:\n \n ```sh\n if [ \"$1\" = \"install\" ] && [ \"$USER\" != \"root\" ]\n then\n echo \"Must be root to install\"\n fi\n ```\n ### Rationale:\n \n ShellCheck found a `test` command followed by a `&`. This runs the test in the background, effectively ignoring it. To specify \"logical AND\" between two commands, use `&&`.\n \n ### Exceptions:\n \n None\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Use && for logical AND. Single & will background and return true. [SC2266]"},{"from": "gpt", "value": "## Use && for logical AND. Single & will background and return true.\n \n ### Problematic code:\n \n ```sh\n if [ \"$1\" = \"--verbose\" ] | [ \"$1\" = \"-v\" ]\n then\n verbose=1\n fi\n ```\n \n ### Correct code:\n \n ```sh\n if [ \"$1\" = \"--verbose\" ] || [ \"$1\" = \"-v\" ]\n then\n verbose=1\n fi\n ```\n ### Rationale:\n \n ShellCheck found a `test` command followed by a `|`. This was undoubtedly intended as a logical OR (`||`).\n \n ### Exceptions:\n \n None\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: GNU `xargs -i` is deprecated in favor of `-I{}` [SC2267]"},{"from": "gpt", "value": "## GNU `xargs -i` is deprecated in favor of `-I{}`\n \n ### Problematic code:\n \n ```sh\n # Implicit replacement string\n xargs -i ls {}\n \n # Explicit replacement string\n xargs -imyfilename ls myfilename\n ```\n \n ### Correct code:\n \n ```sh\n xargs -I {} ls {}\n \n xargs -I filename ls filename\n ```\n ### Rationale:\n \n `xargs -i` is a GNU specific option. It has been deprecated in favor of the POSIX standard option `-I`.\n \n Note that `-i` will implicitly use `{}` as a token if nothing is specified, while `-I` requires it to be explicit.\n \n ### Exceptions:\n \n None.\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Avoid x-prefix in comparisons as it no longer serves a purpose. [SC2268]"},{"from": "gpt", "value": "## Avoid x-prefix in comparisons as it no longer serves a purpose.\n \n ### Problematic code:\n \n ```sh\n [ \"x$pass\" = \"xswordfish\" ]\n \n test x\"$var\" = x \n ```\n \n ### Correct code:\n \n ```sh\n [ \"$pass\" = \"swordfish\" ] \n \n test \"$var\" = \"\"\n ```\n \n ### Rationale:\n \n Some older shells would get confused if the first argument started with a dash, or consisted of `!` or `(`. As a workaround, people would prefix variables and values to be compared with `x` to ensure the left-hand side always started with an alphanumeric character.\n \n POSIX ensures [this is not necessary](https://pubs.opengroup.org/onlinepubs/9699919799/utilities/test.html), and all modern shells now follow suit.\n \n ### Examples:\n \n Bash 1.14 from 1992 incorrectly fails this test. This was fixed for Bash 2.0 in 1996:\n \n ```sh\n var='!'\n [ \"$var\" = \"!\" ]\n ```\n \n Dash 0.5.4 from 2007 incorrectly passes this test. This was fixed for Dash 0.5.5 in 2008: \n \n ```sh\n x='(' y=')'\n [ \"$x\" = \"$y\" ]\n ```\n \n Zsh (while not supported by ShellCheck) fixed the same problem in 2015.\n \n ### Exceptions:\n \n If you are targeting especially old shells, you can ignore this warning (or use a different letter).\n \n ### Related resources:\n \n * [What exactly was the point of `[ \"x$var\" = \"xval\" ]`](https://www.vidarholen.net/contents/blog/?p=1035)?\n * [Wooledge Bash Pitfall #4](https://mywiki.wooledge.org/BashPitfalls#A.5B_.24foo_.3D_.22bar.22_.5D)\n * [Problems With the test Builtin: What Does -a Mean?](http://www.oilshell.org/blog/2017/08/31.html)\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: This variable is assigned to itself, so the assignment does nothing. [SC2269]"},{"from": "gpt", "value": "## This variable is assigned to itself, so the assignment does nothing.\n \n ### Problematic code:\n \n ```sh\n var=\"$var\"\n ```\n \n ### Correct code:\n \n ```sh\n # If the goal is to do nothing\n true\n ```\n \n ### Rationale:\n \n ShellCheck found a variable that is assigned to itself, e.g. `x=$x`. This obviously has no effect.\n \n Double check what the assignment was supposed to do. \n \n ### Exceptions:\n \n None.\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: To assign positional parameters, use `set -- first second ..` (or use `[ ]` to compare). [SC2270]"},{"from": "gpt", "value": "## To assign positional parameters, use `set -- first second ..` (or use `[ ]` to compare).\n \n ### Problematic code:\n \n ```sh\n if [ -z \"$1\" ]\n then\n $1=\"help\"\n fi\n ```\n \n or\n \n ```sh\n if $1=\"help\"\n then\n echo \"Usage: $0 filename\"\n fi\n ```\n \n ### Correct code:\n \n ```sh\n if [ -z \"$1\" ]\n then\n set -- \"help\"\n fi\n ```\n \n or\n \n ```sh\n if [ $1 = \"help\" ]\n then\n echo \"Usage: $0 filename\"\n fi\n ```\n ### Rationale:\n \n You have a command on the form `$2=value`.\n \n If the goal is to assign a new value to the positional parameters, use the `set` builtin: `set -- one two ..` will cause `$1` to be \"one\" and `$2` to be \"two\".\n \n If you instead want to compare the value, use `[ ]` and add spaces: `[ \"$1\" = \"foo\" ]` \n \n ### Exceptions:\n \n None\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: For indirection, use arrays, `declare \"var$n=value\"`, or (for sh) read/eval [SC2271]"},{"from": "gpt", "value": "## For indirection, use arrays, `declare \"var$n=value\"`, or (for sh) read/eval\n \n ### Problematic code:\n \n ```sh\n n=1\n var$n=\"hello\"\n ```\n \n ### Correct code:\n \n For integer indexing in ksh/bash, consider using an indexed array:\n \n ```sh\n n=1\n var[n]=\"hello\"\n echo \"${var[n]}\"\n ```\n \n For string indexing in ksh/bash, use an associative array:\n \n ```sh\n typeset -A var\n n=\"greeting\"\n var[$n]=\"hello\"\n echo \"${var[$n]}\"\n ```\n \n If you actually need a variable with the constructed name in bash, use `declare`:\n \n ```sh\n n=\"Foo\"\n declare \"var$n=42\"\n echo \"$varFoo\"\n ```\n \n For `sh`, with single line contents, consider `read`:\n ```sh\n n=\"Foo\"\n read -r \"var$n\" << EOF\n hello\n EOF\n echo \"$varFoo\"\n ```\n \n or with careful escaping, `eval`:\n \n ```sh\n n=Foo\n eval \"var$n='hello'\"\n echo \"$varFoo\"\n ```\n \n ### Rationale:\n \n `var$n=value` is not a valid way of assigning to a dynamically created variable name in any shell. Please use one of the other methods to assign to names via expanded strings. [Wooledge BashFaq #6](https://mywiki.wooledge.org/BashFAQ/006) has significantly more information on the subject.\n \n \n ### Exceptions:\n \n None\n \n ### Related resources:\n \n * [Wooledge BashFaq #6](https://mywiki.wooledge.org/BashFAQ/006): How can I use variable variables (indirect variables, pointers, references) or associative arrays?\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Command name contains `==`. For comparison, use `[ \"$var\" = value ]`. [SC2272]"},{"from": "gpt", "value": "## Command name contains `==`. For comparison, use `[ \"$var\" = value ]`.\n \n ### Problematic code:\n \n ```sh\n $a/$b==foo/bar\n ```\n \n ### Correct code:\n \n ```sh\n [ \"$a/$b\" = \"foo/bar\" ] \n ```\n ### Rationale:\n \n ShellCheck found a command name that contains a `==`. Most likely, this was intended as a kind of comparison.\n \n To compare two values, use `[ value1 = value2 ]`. Both the brackets and the spaces around the `=` are relevant. \n \n ### Exceptions:\n \n None, though you can quote the `==` to suppress the warning.\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Sequence of `===`s found. Merge conflict or intended as a commented border? [SC2273]"},{"from": "gpt", "value": "## Sequence of `===`s found. Merge conflict or intended as a commented border?\n \n ### Problematic code:\n \n ```sh\n =======\n ```\n \n ### Correct code:\n \n Either resolve the merge conflict, or use `# =======` for a border\n \n ### Rationale:\n \n ShellCheck found a series of `=======`s. If this was supposed to be a border or separator, use a comment.\n \n \n However, it could also be left behind from a source control merge conflict:\n \n ```sh\n <<<<<<< HEAD\n echo \"Goodbye World\"\n =======\n echo \"Hello World!\"\n >>>>>>> mybranch\n ```\n \n In this case, make sure the merge conflict is correctly resolved, and all the markers removed.\n \n ### Exceptions:\n \n None\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Command name starts with `===`. Intended as a commented border? [SC2274]"},{"from": "gpt", "value": "## Command name starts with `===`. Intended as a commented border?\n \n ### Problematic code:\n \n ```sh\n ===================== MAIN SECTION =======================\n ```\n \n ### Correct code:\n \n ```sh\n # ===================== MAIN SECTION =======================\n ```\n ### Rationale:\n \n ShellCheck found a command that starts with a series of `===`s. This may have been intended as a border, but is missing the `#` to turn it into a harmless comment.\n \n ### Exceptions:\n \n None\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Command name starts with `=`. Bad line break? [SC2275]"},{"from": "gpt", "value": "## Command name starts with `=`. Bad line break?\n \n ### Problematic code:\n \n ```sh\n my_variable\n =value\n ```\n \n ### Correct code:\n \n ```sh\n myvariable=value\n ```\n \n ### Rationale:\n \n ShellCheck found a command name starting with a `=`. This was likely not meant as a new command, but instead a continuation from a previous line.\n \n Make sure the `=` is used correctly.\n \n ### Exceptions:\n \n None, though you can quote the value to make ShellCheck ignore it, e.g. `\"=foo\"`.\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: This is interpreted as a command name containing `=`. Bad assignment or comparison? [SC2276]"},{"from": "gpt", "value": "## This is interpreted as a command name containing `=`. Bad assignment or comparison?\n \n ### Problematic code:\n \n ```sh\n \"$var\"=42\n if \"$var\"=42\n then\n true\n fi\n ```\n \n ### Correct code:\n \n ```sh\n var=42\n if [ \"$var\" = 42 ]\n then\n true\n fi\n ```\n \n ### Rationale:\n \n ShellCheck found a command name containing an unquoted equals sign `=`. This was likely intended as either a comparison or an assignment.\n \n To compare two values, use e.g. `[ \"$var\" = \"42\" ]`\n \n To assign a value, use e.g. `var=\"42\"`\n \n ### Exceptions:\n \n None, though you can quote the `=` to make ShellCheck ignore it: `\"$var=42\"`.\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Use `BASH_ARGV0` to assign to `$0` in bash (or use `[ ]` to compare). [SC2277]"},{"from": "gpt", "value": "## Use `BASH_ARGV0` to assign to `$0` in bash (or use `[ ]` to compare).\n \n ### Problematic code:\n \n ```sh\n #!/bin/bash\n $0=myscriptname\n ```\n \n ### Correct code:\n \n ```sh\n #!/bin/bash\n BASH_ARGV0=myscriptname\n ```\n \n ### Rationale:\n \n You appear to be trying to assign a new value to `$0` in a Bash script. To do this, instead assign to the special variable `BASH_ARGV0`.\n \n If you instead wanted to compare the value of `$0`, use a comparison like `[ \"$0\" = \"myname\" ]`.\n \n ### Exceptions:\n \n None.\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: `$0` can't be assigned in Ksh (but it does reflect the current function). [SC2278]"},{"from": "gpt", "value": "## `$0` can't be assigned in Ksh (but it does reflect the current function).\n \n ### Problematic code:\n \n ```sh\n #!/bin/ksh\n $0=myname\n echo \"Usage: $0 --help\"\n ```\n \n ### Correct code:\n \n ```sh\n #!/bin/ksh\n myname() {\n echo \"Usage: $0 --help\"\n }\n myname\n ```\n ### Rationale:\n \n You appear to be trying to assign a new value to `$0` in Ksh.\n \n This is not possible. However, `$0` will reflect the current function name, so if you wrap your code in a function with your chosen name, you can have `$0` expand to it.\n \n ### Exceptions:\n \n If you instead wanted to compare the value of `$0`, use a comparison like `[ \"$0\" = \"myname\" ]`.\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: `$0` can't be assigned in Dash. This becomes a command name. [SC2279]"},{"from": "gpt", "value": "## `$0` can't be assigned in Dash. This becomes a command name.\n \n ### Problematic code:\n \n ```sh\n #!/bin/dash\n $0=myname\n ```\n \n ### Correct code:\n \n `$0` can not be changed in Dash.\n \n ### Rationale:\n \n You appear to be trying to assign a new value to `$0` in Dash.\n \n Dash does not support this. Write around it, or switch to Bash.\n \n ### Exceptions:\n \n If you instead wanted to compare the value of `$0`, use a comparison like `[ \"$0\" = \"myname\" ]`.\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: `$0` can't be assigned this way, and there is no portable alternative. [SC2280]"},{"from": "gpt", "value": "## `$0` can't be assigned this way, and there is no portable alternative.\n \n ### Problematic code:\n \n ```sh\n #!/bin/sh\n $0=myname\n ```\n \n ### Correct code:\n \n `$0` can not be changed in a portable way.\n \n ### Rationale:\n \n You appear to be trying to assign a new value to `$0` in a `sh` script.\n \n There is no portable way to do this. Write around it, or switch to Bash.\n \n ### Exceptions:\n \n If you instead wanted to compare the value of `$0`, use a comparison like `[ \"$0\" = \"myname\" ]`.\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Don't use `$`/`${}` on the left side of assignments. [SC2281]"},{"from": "gpt", "value": "## Don't use `$`/`${}` on the left side of assignments.\n \n ### Problematic code:\n \n ```sh\n $greeting=\"Hello World\"\n ${greeting}=\"Hello World\"\n ```\n \n ### Correct code:\n \n ```sh\n greeting=\"Hello World\"\n ```\n \n Alternatively, if the goal was to assign to a variable whose name is in another variable (indirection), use `declare`:\n \n ```sh\n name=foo\n declare \"$name=hello world\"\n echo \"$foo\"\n ```\n \n Or if you actually wanted to compare the value, use a test expression:\n \n ```sh\n if [ \"$greeting\" = \"hello world\" ]\n then\n echo \"Programmer, I presume?\"\n fi\n ```\n \n ### Rationale:\n \n Unlike Perl or PHP, `$` is not used on the left-hand side of `=` when assigning to a variable.\n \n ### Exceptions\n \n None\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Variable names can't start with numbers, so this is interpreted as a command. [SC2282]"},{"from": "gpt", "value": "## Variable names can't start with numbers, so this is interpreted as a command.\n \n ### Problematic code:\n \n ```sh\n 411toppm=true\n ```\n \n ### Correct code:\n \n ```sh\n _411toppm=true\n ```\n \n ### Rationale:\n \n You appear to be assigning to a variable name that starts with a digit. This is not allowed: variables must start with A-Z, a-z or _.\n \n Switch to a variable name that does not start with a digit.\n \n ### Exceptions:\n \n None\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Use `[ ]` to compare values, or remove spaces around `=` to assign (or quote `'='` if literal). [SC2283]"},{"from": "gpt", "value": "## Use `[ ]` to compare values, or remove spaces around `=` to assign (or quote `'='` if literal).\n \n ### Problematic code:\n \n ```sh\n # Assignment\n var = value\n \n # Comparison\n if $var = value\n then\n echo \"Match\"\n fi\n ```\n \n ### Correct code:\n \n ```sh\n # Assignment\n var=value\n \n # Comparison\n if [ \"$var\" = value ]\n then\n echo \"Match\"\n fi\n ```\n \n ### Rationale:\n \n ShellCheck found an unquoted `=` after a word.\n \n If this was supposed to be a comparison, use square brackets: `[ \"$var\" = value ]`\n \n If this was supposed to be an assignment, remove spaces around `=`: `var=value`\n \n ### Exceptions:\n \n If the `=` was meant literally, quote it:\n \n grep '=true' file.cfg\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Use `[ x = y ]` to compare values (or quote `'=='` if literal). [SC2284]"},{"from": "gpt", "value": "## Use `[ x = y ]` to compare values (or quote `'=='` if literal).\n \n ### Problematic code:\n \n ```sh\n if $var == value\n then\n echo \"Match\"\n fi\n ```\n \n ### Correct code:\n \n ```sh\n if [ \"$var\" = value ]\n then\n echo \"Match\"\n fi\n ```\n \n ### Rationale:\n \n ShellCheck found an unquoted `==` after a word.\n \n This was most likely supposed to be a comparison, so use square brackets as in the correct code.\n \n ### Exceptions:\n \n If the `==` was supposed to be literal, you can quote it to make ShellCheck ignore it:\n \n grep '===' file.js\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Remove spaces around `+=` to assign (or quote `'+='` if literal). [SC2285]"},{"from": "gpt", "value": "## Remove spaces around `+=` to assign (or quote `'+='` if literal).\n \n ### Problematic code:\n \n ```sh\n var += \"my text\"\n ```\n \n ### Correct code:\n \n ```sh\n var+=\"my text\"\n ```\n \n ### Rationale:\n \n ShellCheck found an unquoted `+=` after a word. To append text to a variable, remove spaces around `+=` as in the example.\n \n ### Exceptions:\n \n If the `+=` was supposed to be literal, you can quote it to make ShellCheck ignore it:\n \n grep '+=' files..\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: This empty string is interpreted as a command name. Double check syntax (or use 'true' as a no-op). [SC2286]"},{"from": "gpt", "value": "## This empty string is interpreted as a command name. Double check syntax (or use 'true' as a no-op).\n \n ### Problematic code:\n \n ```sh\n jq \n ''\n file.json\n ```\n \n ### Correct code:\n \n ```sh\n jq \\\n '' \\\n file.json\n ```\n \n ### Rationale:\n \n ShellCheck found an empty string used as a command name. This is never valid. \n \n If the command is intended to do nothing, use `true` aka `:` instead. Otherwise, determine why an empty string ended up as a command name and fix it accordingly. In the example, each line was interpreted as a separate command due to missing line continuations. \n \n ### Exceptions:\n \n None\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: This is interpreted as a command name ending with '/'. Double check syntax. [SC2287]"},{"from": "gpt", "value": "## This is interpreted as a command name ending with '/'. Double check syntax.\n \n ### Problematic code:\n \n ```sh\n df/\n ```\n \n ### Correct code:\n \n ```sh\n df /\n ```\n \n ### Rationale:\n \n ShellCheck found a command name that ends with `/`. Since directories are not valid commands, this is always wrong.\n \n The most common reason is bad quoting or escaping, such as in the example where a space was missing between a command and its argument.\n \n ### Exceptions:\n \n None\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: This is interpreted as a command name ending with apostrophe. Double check syntax. [SC2288]"},{"from": "gpt", "value": "## This is interpreted as a command name ending with apostrophe. Double check syntax.\n \n (also applies to multiple other characters like `.,([{<>}])#\"'`) \n \n ### Problematic code:\n \n ```sh\n var=$(\"wget 'http://www.shellcheck.net/'\")\n echo Usage: $0 {start|stop|restart}\n array=val1, val2, val3\n \n ```\n \n ### Correct code:\n \n ```sh\n var=\"$(wget 'http://www.shellcheck.net/')\"\n echo \"Usage: $0 {start|stop|restart}\"\n array=(val1 val2 val3)\n ```\n \n ### Rationale:\n \n ShellCheck found a command name ending with a symbol, such as a comma, parenthesis, quote, or similar. This is almost always due to a syntax issue in the script.\n \n In the examples, bad quoting and invalid array syntax caused the shell to try to run commands ending in apostrophe, curly brace, and comma, respectively. \n \n ### Exceptions:\n \n If you have a command that *does* end in a symbol, you can ignore this message. \n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: This is interpreted as a command name containing a linefeed. Double check syntax. [SC2289]"},{"from": "gpt", "value": "## This is interpreted as a command name containing a linefeed. Double check syntax.\n \n (or tab)\n \n ### Problematic code:\n \n ```sh\n '''\n This script greets the planet\n '''\n echo \"Hello World\"\n ```\n \n ### Correct code:\n \n ```sh\n # This script greets the planet\n echo \"Hello World\"\n ```\n ### Rationale:\n \n ShellCheck found a command name containing an especially unusual character like a tab or linefeed. This is most likely due to a syntax issue.\n \n In the example, this was due to a Python style documentation string, which a shell will merely interpreted as a multi-line command name sandwiched between two empty strings.\n \n ### Exceptions:\n \n If you have a command name that *does* contain a tab or linefeed you can ignore this message, but... wow. \n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Remove spaces around = to assign. [SC2290]"},{"from": "gpt", "value": "## Remove spaces around = to assign.\n \n ### Problematic code:\n \n ```sh\n export LC_ALL = \"POSIX\"\n ```\n \n ### Correct code:\n \n ```sh\n export LC_ALL=\"POSIX\"\n ```\n \n ### Rationale:\n \n Parameters to `export`, `declare`, `local`, `typeset` and `readonly` may not have spaces around the `=` or `+=` operator. This is the same as for regular variable assignments:\n \n export var = value # Invalid: spaces around =\n export var =value # Invalid: space before =\n export var= value # Invalid: space after =\n export var=value # Valid\n \n This is because each individual argument to these commands is interpreted as a string in the format `name=value`. By adding spaces, you are instead passing the three strings `var`, `=`, `value`, none of which follow this format.\n \n ### Exceptions:\n \n None\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Quote repeated spaces to avoid them collapsing into one. [SC2291]"},{"from": "gpt", "value": "## Quote repeated spaces to avoid them collapsing into one.\n \n ### Problematic code:\n \n ```sh\n echo Hello World\n ```\n \n ### Correct code:\n \n ```sh\n echo \"Hello World\"\n ```\n \n ### Rationale:\n \n ShellCheck found multiple unquoted spaces between words passed to `echo`. Due to the way arguments are interpreted and passed in the shell, these will collapse into a single space:\n \n ```\n $ echo Hello World\n Hello World\n ```\n \n If you want to output multiple spaces, such as when creating a notice or banner, make sure the spaces are quoted, e.g. by adding (or extending) double quotes to include them:\n \n ```\n $ echo \"Hello World\"\n Hello World\n ```\n \n ### Exceptions:\n \n If you're aware of this behavior and didn't want multiple spaces to show up in the output, you can either remove the unnecessary spaces or [[ignore]] this issue.\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Prefer `[[ ]]` over `[ ]` for tests in Bash/Ksh. [SC2292]"},{"from": "gpt", "value": "## Prefer `[[ ]]` over `[ ]` for tests in Bash/Ksh.\n \n This is an [[optional]] suggestion. It must be explicitly enabled with a [[directive]] `enable=require-double-brackets` in a `# shellcheck` comment or `.shellcheckrc`\n \n ### Problematic code:\n \n ```sh\n [ -e /etc/issue ] \n ```\n \n ### Correct code:\n \n ```sh\n [[ -e /etc/issue ]]\n ```\n \n ### Rationale:\n \n ShellCheck has been explicitly asked to warn about uses of `[ .. ]` in favor of the extended Bash/Ksh test `[[ .. ]]`.\n \n `[[ .. ]]` suppresses word splitting and globbing, supports a wider variety of tests, and is generally safer and better defined than `[ .. ]`. For an in-depth list of differences, see the Related Resources. \n \n ### Exceptions:\n \n This check is not enabled by default, and may have been turned on for your current project by someone who wants it enforced. You can still [[ignore]] it with a directive.\n \n This suggestion does not trigger for Sh or Dash scripts, even when explicitly enabled, as these shells don't support `[[ .. ]]`. \n \n ### Related resources:\n \n * BashFAQ 031: [What is the difference between test, \\[ and \\[\\[ ?](https://mywiki.wooledge.org/BashFAQ/031)\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: When eval'ing @Q-quoted words, use * rather than @ as the index. [SC2293]"},{"from": "gpt", "value": "## When eval'ing @Q-quoted words, use * rather than @ as the index.\n \n ### Problematic code:\n \n ```sh\n eval \"$MYCOMMAND ${@@Q}\"\n ```\n \n ### Correct code:\n \n ```sh\n eval \"$MYCOMMAND ${*@Q}\"\n ```\n \n ### Rationale:\n \n ShellCheck noticed that you are calling `eval` and including an escaped array. However, the array is passed as multiple arguments and relies on being implicitly joined together to form a single shell string, which `eval` can then evaluate.\n \n Instead, prefer building your shell string with explicit string concatenation by using `*` instead of `@` for the index, such as `${*@Q}` or `${array[*]@Q}`.\n \n This suggestion is equivalent to [[SC2124]], but for `eval` arguments rather than string variables.\n \n ### Exceptions:\n \n None.\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: eval negates the benefit of arrays. Drop eval to preserve whitespace/symbols (or eval as string). [SC2294]"},{"from": "gpt", "value": "## eval negates the benefit of arrays. Drop eval to preserve whitespace/symbols (or eval as string).\n \n ### Problematic code:\n \n ```sh\n check() {\n eval \"$@\" || exit\n }\n ```\n \n ### Correct code:\n \n ```sh\n check() {\n \"$@\" || exit\n }\n ```\n \n ### Rationale:\n \n ShellCheck found `eval` used on an array (or equivalently, `\"$@\"`). This is problematic because it effectively throws away all boundary information and rebuilds it from shell words.\n \n Let's say you invoke `check sed -i '$d' \"my file.txt\"`:\n \n `eval \"$@\"` will:\n 1. Join the elements on spaces: `sed -i $d my file.txt`\n 2. Split the string on shell word boundaries: `sed`, `-i`, `$d`, `my` `file.txt`\n 3. Perform shell expansions (assuming `$d` is unset): `sed`, `-i`, `my`, `file.txt`\n 4. Execute the first element as the command and the rest as its arguments, as if running `sed -i 'my' 'file.txt'`\n \n `\"$@\"` will\n 1. Execute the first element as the command and the rest as its arguments, as if running `sed -i '$d' 'my file.txt'`\n \n Note that while `\"$@\"` is essentially always better than `eval \"$@\"`, it's easy to unintentionally introduce a dependency on bad behavior through the shell debugging anti-strategy of \"adding quotes until it works\":\n \n ```\n # Works with problematic example because of double-escaping, fails with correct example\n check ls -l \"'My File.txt'\" \n \n # Works with correct example the way it was always intended:\n check ls -l \"My File.txt\" \n ```\n \n The correct example is still better, but the function invocation has to be tweaked as well.\n \n ### Exceptions:\n \n If each of the array elements is a carefully escaped shell command or word, use `*` instead of `@` to explicitly join the elements on spaces which is what would happen anyways:\n \n ```\n on_exit=(\n 'rm /tmp/myfile; '\n 'echo \"Finished on $(date)\" > log.txt; '\n )\n \n # Equivalent to `eval \"${on_exit[@]}\"`, but more explicit\n eval \"${on_exit[*]}\"\n \n # Even better in this case, as it does not require\n # semicolons and commands don't interfere:\n for cmd in \"${on_exit[@]}\"\n do\n eval \"$cmd\"\n done\n ```\n \n If you require `eval` for another part of the command, explicitly transform the array into a series of escaped shell words. This ensures that the array elements will `eval` back to themselves:\n \n ```\n # Assumed to be outside of our control, \n # otherwise we would output this in an array as well:\n COMMAND='dialog --menu \"Choose file:\" 15 40 4'\n \n # Our array:\n array=(\n 1 \"My File.txt\"\n 2 \"My Other File.txt\"\n )\n eval \"$COMMAND ${array[*]@Q}\" # Bash 4+\n eval \"$COMMAND $(printf \"%q \" \"${array[@]}\")\" # Bash 1+\n ```\n \n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Expansions inside `${..}` need to be quoted separately, otherwise they will match as a pattern. [SC2295]"},{"from": "gpt", "value": "## Expansions inside `${..}` need to be quoted separately, otherwise they will match as a pattern.\n \n ### Problematic code:\n \n ```sh\n relative_path() {\n printf '%s\\n' \"${2#$1}\"\n }\n \n # Results in \"/tmp/King_Kong_[1933]/extras/trailer.mkv\" because the prefix fails to match\n relative_path \"/tmp/King_Kong_[1933]/\" \"/tmp/King_Kong_[1933]/extras/trailer.mkv\"\n \n # Results in \"cover.jpg\" even though the prefix is different\n relative_path \"/tmp/King_Kong_[1933]/\" \"/tmp/King_Kong_3/cover.jpg\"\n \n ```\n \n ### Correct code:\n \n ```sh\n relative_path() {\n printf '%s\\n' \"${2#\"$1\"}\"\n }\n # Results in \"extras/trailer.mkv\" as expected\n relative_path \"/tmp/King_Kong_[1933]/\" \"/tmp/King_Kong_[1933]/extras/trailer.mkv\"\n \n # Results in \"/tmp/King_Kong_3/cover.jpg\" as expected\n relative_path \"/tmp/King_Kong_[1933]/\" \"/tmp/King_Kong_3/cover.jpg\"\n ```\n \n ### Rationale:\n \n When using expansions in a parameter expansion prefix/suffix expression, the expansion needs to be quoted separately or it will match as a pattern. The quotes around the outer parameter expansion does not protect against this.\n \n This means that any variable that contains e.g. brackets, asterisks or question marks may not match as expected. In the example, `[1933]` was interpreted as a pattern character range and would therefore match `/tmp/King_Kong_3/` but not `/tmp/King_Kong_[1933]/` as was the intention.\n \n ### Exceptions:\n \n If you wanted to treat the string as a pattern, such as `suffix=\".*\"; file=\"${var%$suffix}\";` then you can [[ignore]] this suggestion. \n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Parameter expansions can't start with `{`. Double check syntax. [SC2296]"},{"from": "gpt", "value": "## Parameter expansions can't start with `{`. Double check syntax.\n \n (or any other character)\n \n ### Problematic code:\n \n ```sh\n echo \"Hello ${{name}\"\n ```\n \n ### Correct code:\n \n ```sh\n echo \"Hello ${name}\"\n ```\n \n ### Rationale:\n \n ShellCheck found a parameter expansion `${something}` that starts with an invalid character. In the example, this was caused by accidentally duplicating the `{` in `${{name}`.\n \n Double check the syntax of what you're trying to do.\n \n ### Exceptions:\n \n Some Zsh specific parameter expansions like `${(q)value}` trigger this warning, but ShellCheck does not support Zsh.\n \n If this warning triggers in code that works on Bash, Ksh, Dash or Sh, please [submit a bug](https://github.com/koalaman/shellcheck/issues/new).\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Double quotes must be outside `${}`: `${\"invalid\"}` vs `\"${valid}\"`. [SC2297]"},{"from": "gpt", "value": "## Double quotes must be outside `${}`: `${\"invalid\"}` vs `\"${valid}\"`.\n \n ### Problematic code:\n \n ```sh\n echo ${\"USER\"}\n ```\n \n ### Correct code:\n \n ```sh\n echo \"${USER}\"\n ```\n \n ### Rationale:\n \n ShellCheck found a parameter expansion containing what appears to be a quoted variable name.\n \n While the parameter expansion itself must be quoted, as in `\"${valid}\"`, the quotes may not appear inside the `{}` as in `${\"invalid\"}`.\n \n Also note that translated strings like `$\"Hello\"` may not use curly braces.\n \n ### Exceptions:\n \n None\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: `${$x}` is invalid. For expansion, use ${x}. For indirection, use arrays, ${!x} or (for sh) eval. [SC2298]"},{"from": "gpt", "value": "## `${$x}` is invalid. For expansion, use ${x}. For indirection, use arrays, ${!x} or (for sh) eval.\n \n (or `${${x}}` is invalid)\n \n ### Problematic code:\n \n ```sh\n # Expecting $RETRIES or 3 if unset\n retries=${$RETRIES:-3}\n ```\n \n or\n \n ```sh\n mypath=\"/tmp/foo.txt\"\n var=mypath\n result=${$var##*/} # Expecting ${mypath##*/}, i.e. 'foo.txt'\n ```\n \n ### Correct code:\n \n ```sh\n retries=${RETRIES:-3}\n ```\n \n or\n \n ```sh\n mypath=\"/tmp/foo.txt\"\n var=mypath\n result=${!var}\n result=${result##*/}\n \n ```\n \n ### Rationale:\n \n ShellCheck found a parameter expansion `${..}` where the first element was a second parameter expansion, either `${$x..}` or `${${x}..}`. This is not valid.\n \n In the first example, the extra `$` was unintentional and should simply be deleted.\n \n In the second example, `${$var##*/}` was used in the hopes that it would expand to `${myvar##*/}` and subsequently strip the path. This is not possible, and `var` must instead be expanded indirectly in a separate step, before the path can be stripped as usual. More information and other approaches can be found in the description of [[SC2082]].\n \n ### Exceptions:\n \n None\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Parameter expansions can't be nested. Use temporary variables. [SC2299]"},{"from": "gpt", "value": "## Parameter expansions can't be nested. Use temporary variables.\n \n ### Problematic code:\n \n ```sh\n path=\"/path/to/MyFile.mp3\"\n echo \"Playing ${${path##*/}%.*}\" # Expect: Playing MyFile\n ```\n \n ### Correct code:\n \n ```sh\n path=\"/path/to/MyFile.mp3\"\n tmp=${path##*/}\n echo \"Playing ${tmp%.*}\"\n ```\n \n ### Rationale:\n \n ShellCheck found what appears to be a nested parameter expansion. In the example, it was hoping to combine `${var##*/}` to strip the directory and `${var%.*}` to strip the extension.\n \n Parameter expansions can't be nested. Use temporary variables instead, so that each parameter expansion only does a single operation.\n \n Alternatively, if the goal is to dynamically generate and expand a variable name, see [[SC2082]].\n \n ### Exceptions:\n \n None\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Parameter expansion can't be applied to command substitutions. Use temporary variables. [SC2300]"},{"from": "gpt", "value": "## Parameter expansion can't be applied to command substitutions. Use temporary variables.\n \n ### Problematic code:\n \n ```sh\n echo \"Building ${$(git rev-parse --show-toplevel)##*/}\"\n ```\n \n ### Correct code:\n \n ```sh\n tmp=$(git rev-parse --show-toplevel)\n echo \"Building ${tmp##*/}\"\n ```\n ### Rationale:\n \n ShellCheck found a parameter expansion that begins with a command substitution, such as `$(..)` or `` `..` ``. This is not valid. Parameter expansion only works on variables (normal or special).\n \n In the example, the user hoped to apply the construct `${var##*/}`, stripping the path, to the current git root directory as output by `git rev-parse --show-toplevel`. Since parameter expansion only works on variable, the command substitution must be assigned to a variable first like in the correct example.\n \n If the goal was instead to dynamically generate a variable name to expand, see [[SC2082]].\n \n ### Exceptions:\n \n None\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Parameter expansion starts with unexpected quotes. Double check syntax. [SC2301]"},{"from": "gpt", "value": "## Parameter expansion starts with unexpected quotes. Double check syntax.\n \n ### Problematic code:\n \n ```sh\n echo ${\"Hello World\"}\n ```\n \n ### Correct code:\n \n ```sh\n echo $\"Hello World\"\n ```\n \n ### Rationale:\n \n ShellCheck found a parameter expansion `${...}` that contains an unexpected syntax element, such as single or double quotes.\n \n In the example, this was due to wrapping a translated string `$\"..\"` with curly braces, which is not valid.\n \n It is unclear what the intention is with invalid expansions like `${'foo'}`, `${$\"foo\"}`, so please look up how to do what you were trying to do.\n \n ### Exceptions:\n \n If this warning triggers for working code, please [submit a bug](https://github.com/koalaman/shellcheck/issues/new).\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: This loops over values. To loop over keys, use `\"${!array[@]}\"`. [SC2302]"},{"from": "gpt", "value": "## This loops over values. To loop over keys, use `\"${!array[@]}\"`.\n \n Plus companion warning [[SC2303]]: `i is an array value, not a key. Use directly or loop over keys instead.`\n \n ### Problematic code:\n \n ```sh\n array=(foo bar)\n for v in \"${array[@]}\"\n do\n echo \"Value is ${array[$v]}\"\n done\n ```\n \n ### Correct code:\n \n Either loop over values \n \n ```sh\n for v in \"${array[@]}\"\n do\n echo \"Value is $v\"\n done\n ```\n \n or loop over keys:\n \n ```sh\n for k in \"${!array[@]}\" # Note `!`\n do\n echo \"Key is $k\"\n echo \"Value is ${array[$k]}\"\n done\n ```\n \n ### Rationale:\n \n ShellCheck found a `for` loop over array *values*, where the variable is used as an array *key*. \n \n In the problematic example, the loop will print `Value is foo` twice. On the second iteration, `v=bar`, and `bar` is unset and considered zero, so `${array[$v]}` becomes `${array[bar]}` becomes `${array[0]}` becomes `foo`.\n \n If you don't care about the key, simply loop over array values and use `$v` to refer to the array value, like in the first correct example.\n \n If you do want the key, loop over array keys with `\"${!array[@]}\"`, use `$k` to refer to the array key, and `${array[$k]}` to refer to the array value.\n \n ### Exceptions:\n \n If you do want to use values from the arrays as keys in the same array, you can [[ignore]] these messages with a directive:\n \n ```sh\n declare -A fatherOf=(\n [\"Eric Bloodaxe\"]=\"Harald Fairhair\"\n [\"Harald Fairhair\"]=\"Halfdan the Black\"\n [\"Halfdan the Black\"]=\"Gudrød the Hunter\"\n [\"Gudrød the Hunter\"]=\"Halfdan the Mild\"\n )\n \n # shellcheck disable=SC2302,SC2303\n for i in \"${fatherOf[@]}\" \n do\n echo \"${fatherOf[$i]:-(missing)} begat $i\"\n done\n ```\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: `i` is an array value, not a key. Use directly or loop over keys instead. [SC2303]"},{"from": "gpt", "value": "## `i` is an array value, not a key. Use directly or loop over keys instead.\n \n See companion warning [[SC2302]]\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: `*` must be escaped to multiply: `\\*`. Modern `$((x * y))` avoids this issue. [SC2304]"},{"from": "gpt", "value": "## `*` must be escaped to multiply: `\\*`. Modern `$((x * y))` avoids this issue.\n \n ### Problematic code:\n \n ```sh\n result=$(expr 2 * 3)\n ```\n \n ### Correct code:\n \n ```sh\n # Modern, efficient, POSIX standard approach\n result=$(( 2 * 3 ))\n \n # Older, slower approach\n result=$(expr 2 \\* 3)\n ```\n ### Rationale:\n \n ShellCheck found an `expr` command whose operator is an unescaped asterisk `*`.\n \n When using `expr`, each argument is expanded the same way as for any other command. This means that `expr 2 * 3` will turn into `expr 2 Desktop Documents Downloads Music Pictures 3` depending on the files in the current directory, causing an error like `expr: syntax error: unexpected argument ‘Desktop’`\n \n The best way to avoid this is to avoid `expr` and instead use `$((..))` instead. If you for any reason prefer the 200x slower, heavyweight process of forking a new process, you can escape the `*`. Both ways are demonstrated in the correct example.\n \n ### Exceptions:\n \n None\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Quote regex argument to expr to avoid it expanding as a glob. [SC2305]"},{"from": "gpt", "value": "## Quote regex argument to expr to avoid it expanding as a glob.\n \n ### Problematic code:\n \n ```sh\n expr \"$input\" : [0-9]*\n ```\n \n ### Correct code:\n \n ```sh\n expr \"$input\" : \"[0-9]*\"\n ```\n \n ### Rationale:\n \n ShellCheck found an `expr` command using `:` to match a regex, but the regex is not quoted and therefore being treated as a glob.\n \n This means that if the problematic code is ever executed in a directory containing a file matching `[0-9]*`, such as `2021-reports` or `12 Angry Men [1957].mkv`, it will be replaced be replaced and cause the command to error or incorrectly match.\n \n The regex should be quoted to avoid this, like in the correct example.\n \n ### Exceptions:\n \n None\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Escape glob characters in arguments to expr to avoid pathname expansion. [SC2306]"},{"from": "gpt", "value": "## Escape glob characters in arguments to expr to avoid pathname expansion.\n \n ### Problematic code:\n \n ```sh\n f=$(expr \"$c\" * 9 / 5 + 32)\n ```\n \n ### Correct code:\n \n Prefer rewriting to a modern style (see [[SC2003]]):\n \n ```sh\n f=$((c * 9 / 5 + 32))\n ```\n \n If you do not wish to do so, at least escape the glob characters when passing them to `expr`:\n \n ```sh\n f=$(expr \"$c\" \\* 9 / 5 + 32)\n ```\n \n ### Rationale:\n \n `expr` is a command so `expr 2 * 2` will consider `*` to mean \"all files in the current directory\". This causes the expression to fail to evaluate unless you are in an empty directory with the `failglob` and `nullglob` options turned off. \n \n Prefer rewriting it using the modern, POSIX standard arithmetic expansion `$((..))`. If you do not wish to do so, you can escape any characters like `*` to avoid the shell performing pathname expansion on them.\n \n ### Exceptions:\n \n None\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: 'expr' expects 3+ arguments but sees 1. Make sure each operator/operand is a separate argument, and escape <>&|. [SC2307]"},{"from": "gpt", "value": "## 'expr' expects 3+ arguments but sees 1. Make sure each operator/operand is a separate argument, and escape <>&|.\n \n ### Problematic code:\n \n ```sh\n # | not escaped\n expr 1 | 2\n # > not escaped\n expr \"$foo\" >= \"$bar\"\n \n # Missing spaces around +\n expr 1+2\n # Unexpected quoting around an expression\n expr \"1 + 2\"\n ```\n \n ### Correct code:\n \n ```sh\n expr 16 \\| 7\n expr \"$foo\" \\>= \"$bar\"\n expr 1 + 2\n ```\n \n ### Rationale:\n \n ShellCheck found an `expr` command with 1 or 2 arguments. `expr` normally expects 3 or more.\n \n Generally, this happens for one of two reasons:\n \n * You are using an operator like `|`, `&`, `>`, `>=`, `<`, `<=`, which needs to be escaped to avoid the shell interpreting it as a pipe, backgrounded command, or redirection.\n * You don't have spaces around operators and operands (or have bad quotes) which causes them not to be separate arguments.\n \n Make sure each operator or operand to `expr` is a separate argument, and that anything containing shell metacharacters is escaped. The correct code shows examples of each.\n \n ### Exceptions:\n \n None\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: `expr length` has unspecified results. Prefer `${#var}`. [SC2308]"},{"from": "gpt", "value": "## `expr length` has unspecified results. Prefer `${#var}`.\n \n or `'expr match' has unspecified results. Prefer 'expr str : regex'.` \n or `'expr substr' has unspecified results. Prefer 'cut' or ${var#???}.` \n or `'expr index' has unspecified results. Prefer x=${var%%[chars]*}; $((${#x}+1)).` \n \n ### Problematic code:\n \n ```sh\n # Find length of string\n length=$(expr length \"$var\")\n \n # Match string against regex\n expr match \"$input\" \"[0-9]*\"\n \n # Find character index in string\n pos=$(expr index \"$input\" \":\")\n \n # Get substring by index\n col2=$(expr substr \"foo bar baz\" 8 5)\n ```\n \n ### Correct code:\n \n ```sh\n # Find length of string\n length=${#var}\n \n # Match string against regex\n expr \"$input\" : \"[0-9]*\"\n \n # Find character index in string\n pos=${input%%:*} pos=$((${#pos}+1))\n \n # Get substring by index (bash)\n str=\"foo bar baz\"\n col2=\"${str:7:5}\"\n \n # Get substring by index (POSIX)\n col2=\"$(printf 'foo bar baz\\n' | cut -c 8-12)\"\n ```\n ### Rationale:\n \n You are using a `expr` with `length`, `match`, `index`, or `substr`. These forms did not make it into POSIX, and fail on platforms like MacOS and FreeBSD. Consider replacing them with portable equivalents:\n \n #### `length`\n can be trivially replaced with `${#var}`\n \n #### `match`\n can be trivially replaced with the POSIX form `expr str : regex`\n \n #### `index`\n if you only need a numerical index as part of trying to extract a piece of the string, consider replacing it with parameter expansion:\n \n ```\n str=\"mykey=myvalue\"\n key=\"${str%%=*}\" # Remove everything after first =, no index required\n value=\"${str#*=}\" # Remove everything before first =, no index required\n ```\n \n otherwise, you can find the index of the first `=` using parameter expansion and string length:\n \n ```\n str=\"mykey=myvalue\"\n x=${str%%=*} # Assign x=\"mystr\"\n index=$((${#x}+1)) # Add 1 to length of x\n ```\n \n #### `substr`\n \n Extract a substring via character index is generally fragile. For example, in this example, any minor changes to the format, including just the version increasing from 8.9 to 8.10, will cause the following snippet to fail:\n \n ```\n str=\"VIM - Vi IMproved 8.2 (2019 Dec 12, compiled Feb 15 2021 12:29:39)\"\n version=$(expr substr \"$str\" 19 3)\n ```\n \n Instead, consider a different approach:\n \n ```\n x=\"${str%% (*}\" # Delete ` (` and everything after, giving \"VIM - Vi IMproved 8.2\"\n version=\"${x##* }\" # Delete everything before last space, giving \"8.2\"\n \n # Get the fifth word separated by spaces\n IFS=\" \" read -r _ _ _ _ version _ << EOF\n $str\n EOF\n ```\n \n If you still want to use character index, this is trivially done in Bash/Ksh with `${var:offset:length}` (0-based).\n \n In POSIX, you can generally use `cut`, though be careful if the value can contain multiple lines.\n \n ### Exceptions:\n \n If you know your script will only run on platforms where these forms are supported, like GNU or BusyBox, you can [[ignore]] this warning.\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: -eq treats this as a variable. Use = to compare as string (or expand explicitly with $var) [SC2309]"},{"from": "gpt", "value": "## -eq treats this as a variable. Use = to compare as string (or expand explicitly with $var)\n \n ### Problematic code:\n \n ```sh\n read -p \"Continue? [y/n] \" var\n [ \"$var\" -eq \"n\" ​] && exit 1\n ```\n \n ### Correct code:\n \n ```sh\n #read -p \"Continue? [y/n] \" var\n [ \"$var\" = \"n\" ​] && exit 1\n ```\n \n ### Rationale:\n \n ShellCheck found a string used as an argument to a numerical operator like `-eq`, `-ne`, `-lt`, `-ge`. Such strings will be treated as arithmetic expressions, meaning `n` will refer to a variable `$n`, and `24/12` will be evaluated into `2`. \n \n In the problematic example, the intention was instead to compare `\"n\"` as a string, so it should use the equivalent string operator instead, in this case `=`.\n \n ### Exceptions:\n \n It is perfectly valid to use variables as operands. ShellCheck will not flag any value that is an unquoted variable name assigned in the script:\n \n a=42; [[ \"a\" -eq 0 ]] # Flagged due to quotes\n [[ b -eq 0 ]] # Flagged due to not being assigned\n c=42; [[ c -eq 0 ]] # Not flagged\n \n However, ShellCheck does not know whether you intended `foo/bar` to be division or a file path. \n \n If you intended to divide `$foo` and `$bar`, you can either make it explicit with `[[ $((foo/bar)) -ge 0 ]]`, or simply [[ignore]] the warning.\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: This function is invoked in an 'if' condition so set -e will be disabled. Invoke separately if failures should cause the script to exit. [SC2310]"},{"from": "gpt", "value": "## This function is invoked in an 'if' condition so set -e will be disabled. Invoke separately if failures should cause the script to exit.\n \n (This warning is optional and must be explicitly enabled)\n \n ### Problematic code:\n \n ```sh\n #!/bin/sh\n #shellcheck enable=check-set-e-suppressed\n \n set -e\n \n backup() {\n cp *.txt /backup\n rm *.txt # Runs even if copy fails!\n }\n \n if backup\n then\n echo \"Backup successful\"\n fi\n ```\n \n ### Correct code:\n \n ```sh\n #!/bin/sh\n #shellcheck enable=check-set-e-suppressed\n \n set -e\n \n backup() {\n cp *.txt /backup\n rm *.txt\n }\n \n backup\n echo \"Backup successful\"\n ```\n \n ### Rationale:\n \n ShellCheck found a function used as a condition in a script where `set -e` is enabled. This means that the function will run without `set -e`, and will power through any errors.\n \n This applies to `if`, `while`, and `until` statements, commands negated with `!`, as well as the left-hand side of `||` and `&&`. It does not matter how deeply the command is nested in such a structure.\n \n In the problematic example, the intent was that an error like `cp: error writing '/backup/important.txt': No space left on device` would cause the script to abort. Instead, since the function is invoked in an `if` statement, the script will proceed to delete all the files even though it failed to back them up.\n \n The fix is to call it outside of an `if` statement. There is no point in checking whether the command succeeded, since the script would abort if it didn't. You may also want to consider replacing `set -e` with explicit `|| exit` after every relevant command to avoid such surprises.\n \n ### Exceptions:\n \n If you don't care that the function runs without `set -e`, you can disable this warning. \n \n ### Related resources:\n \n * BashFaq #105: [Why doesn't set -e (or set -o errexit, or trap ERR) do what I expected?](https://mywiki.wooledge.org/BashFAQ/105)\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Bash implicitly disabled set -e for this function invocation because it's inside a command substitution. Add set -e; before it or enable inherit_errexit. [SC2311]"},{"from": "gpt", "value": "## Bash implicitly disabled set -e for this function invocation because it's inside a command substitution. Add set -e; before it or enable inherit_errexit.\n \n ### Problematic code:\n \n ```sh\n #!/bin/bash\n \n #shellcheck enable=check-set-e-suppressed\n set -e\n \n deploy() {\n make -j \"$(nproc)\" foo test\n cp ./foo /var/www/example.com/cgi-bin\n ./foo --version 2>&1\n }\n \n version=$(deploy)\n echo \"Successfully deployed $version\"\n ```\n \n ### Correct code:\n \n ```sh\n #!/bin/bash\n \n #shellcheck enable=check-set-e-suppressed\n set -e\n shopt -s inherit_errexit\n \n deploy() {\n make -j \"$(nproc)\" foo test\n cp ./foo /var/www/example.com/cgi-bin\n ./foo --version 2>&1\n }\n \n version=$(deploy)\n echo \"Successfully deployed $version\"\n ```\n ### Rationale:\n \n ShellCheck found a Bash function invoked in a command substitution with `set -e` enabled.\n \n Unlike other shells, Bash disables `set -e` in command substitution by default. This means that the function will not exit on error. \n \n In the problematic code, the hope was that the function (and therefore the script) would fail if the build and test suite failed. Instead, the deployment continues even if the tests fail. \n \n This can be fixed by either using `version=$(set -e; deploy)` or by enabling `inherit_errexit` as in the correct example.\n \n ### Exceptions:\n \n If you don't care that the function runs without `set -e`, you can [[ignore]] this warning.\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Consider invoking this command separately to avoid masking its return value (or use '|| true' to ignore). [SC2312]"},{"from": "gpt", "value": "## Consider invoking this command separately to avoid masking its return value (or use '|| true' to ignore).\n \n This is an optional suggestion enabled with `shellcheck -o check-extra-masked-returns` or `enable=check-extra-masked-returns` in a `# shellcheck` directive or `.shellcheckrc`.\n \n ### Problematic code:\n \n ```sh\n set -e\n cd \"$(get_chroot_dir)/etc\"\n tar xf \"${config}\"\n ```\n \n ### Correct code:\n \n ```sh\n set -e\n dir=\"$(get_chroot_dir)\"\n cd \"${dir}/etc\"\n tar xf \"${config}\"\n ```\n \n ### Correct code: (with correction)\n \n ```sh\n set -e\n dir=\"$(get_chroot_dir)\"\n [[ -d \"${dir}\" ]] || exit 1\n cd \"${dir}/etc\"\n tar xf \"${config}\"\n ```\n \n ### Rationale:\n \n In the problematic example, the exit code for `get_chroot_dir` is ignored because it is used in a command substitution in the argument of another command.\n \n If the command shows `error: Can't determine chroot` and exits with failure without outputting a directory, then the command being run will be `cd \"/etc\"` and the script will proceed to overwrite the host system's configuration.\n \n By assigning it to a variable first, the exit code of the command will propagate into the exit code of the assignment, so that it can be checked explicitly with `if` or implicitly with `set -e`.\n \n ### Exceptions:\n \n If you don't care about the command's exit status, or already handle it through a side channel like `<(cmd; echo $? > status)`, then you can either [[ignore]] the suggestion with a directive, or use `|| true` (or `|| :`) to suppress it.\n \n ### Related resources:\n \n https://mywiki.wooledge.org/BashPitfalls#cmd1_.26.26_cmd2_.7C.7C_cmd3\n \n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Quote array indices to avoid them expanding as globs. [SC2313]"},{"from": "gpt", "value": "## Quote array indices to avoid them expanding as globs.\n \n ### Problematic code:\n \n ```sh\n read -r foo[index]\n ```\n \n ### Correct code:\n \n ```sh\n read -r \"foo[index]\"\n ```\n \n ### Rationale:\n \n ShellCheck found an array element passed to read, where the `[]` was not quoted. This means the array index `[index]` will be treated as a glob range, and the word may be replaced or trigger `failglob`. \n \n In the problematic example, having a directory named `food` will cause the command to become `read -r food` instead, since `food` matches the glob `foo[index]`. The result is assigning a value to the wrong variable.\n \n Quote or escape the pattern as shown to ensure it always reads into the array `foo` at index `index`. \n \n ### Exceptions:\n \n None.\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: In bats, `!` does not cause a test failure. [SC2314]"},{"from": "gpt", "value": "## In bats, `!` does not cause a test failure.\n \n ### Problematic code:\n \n ```sh\n #!/usr/bin/env bats\n \n @test \"test\" {\n # ... code\n ! test_file_exists\n # ... more code\n }\n ```\n \n ### Correct code:\n \n ```sh\n #!/usr/bin/env bats\n \n @test \"test\" {\n # ... code\n run ! test_file_exists\n # ... more code\n }\n ```\n \n ### Rationale:\n \n Bats uses `set -e` and `trap ERR` to catch test failures as early as possible.\n Although the return code of a `!` negated command is inverted, they will never trigger `errexit`, due to a bash design decision (see [Related Resources](#related-resources)).\n This means that tests which use `!` can never fail.\n \n Starting with bats 1.5.0 you can use `!` inside `run`.\n If you are still using an older bats version, you can rewrite `! ` to ` && exit 1`.\n \n ### Exceptions:\n \n The return code of the last command in the test will be the exit code of the test function.\n This means that you can use `! ` on the last line of the test and it will still fail appropriately.\n However, you are encouraged to still use `run !` in this case for consistency.\n \n ### Related resources:\n \n * [SC2251: This ! is not on a condition and skips errexit](SC2251.md)\n * [Stackoverflow: Why do I need parenthesis In bash `set -e` and negated return code](https://stackoverflow.com/a/39582012/760746)\n * [bash manpage](https://linux.die.net/man/1/bash) (look at `trap [-lp] [[arg] sigspec ...]`): \n > The ERR trap is not executed [...] if the command's return value is being inverted via !\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: In bats, `!` does not cause a test failure. Fold the `!` into the conditional! [SC2315]"},{"from": "gpt", "value": "## In bats, `!` does not cause a test failure. Fold the `!` into the conditional!\n \n ### Problematic code:\n \n ```sh\n #!/usr/bin/env bats\n \n @test \"test\" {\n # ... code\n ! [ $status == 0 ]\n # ... more code\n }\n ```\n \n ### Correct code:\n \n ```sh\n #!/usr/bin/env bats\n \n @test \"test\" {\n # ... code\n [ $status != 0 ]\n # ... more code\n }\n ```\n \n ### Rationale:\n \n Bats uses `set -e` and `trap ERR` to catch test failures as early as possible.\n Although the return code of a `!` negated command is inverted, they will never trigger `errexit`, due to a bash design decision (see [Related Resources](#related-resources)).\n This means that tests which use `!` can never fail.\n \n ### Exceptions:\n \n The return code of the last command in the test will be the exit code of the test function.\n This means that you can use `! ` on the last line of the test and it will still fail appropriately.\n However, you are encouraged to still transform the code in this case for consistency.\n \n ### Related resources:\n \n * [SC2314: In bats, ! does not cause a test failure (for non-conditionals)](SC2314)\n * [SC2251: This ! is not on a condition and skips errexit](SC2251.md)\n * [Stackoverflow: Why do I need parenthesis In bash `set -e` and negated return code](https://stackoverflow.com/a/39582012/760746)\n * [bash manpage](https://linux.die.net/man/1/bash) (look at `trap [-lp] [[arg] sigspec ...]`): \n > The ERR trap is not executed [...] if the command's return value is being inverted via !\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: This applies local to the variable named readonly, which is probably not what you want. Use a separate command or the appropriate `declare` options instead. [SC2316]"},{"from": "gpt", "value": "## This applies local to the variable named readonly, which is probably not what you want. Use a separate command or the appropriate `declare` options instead.\n \n \n ### Problematic code:\n \n ```sh\n local readonly foo=3\n readonly export bar=4\n ```\n \n ### Correct code:\n \n ```sh\n local foo=3\n readonly foo\n \n readonly bar=4\n export bar\n ```\n \n or \n \n ```\n declare -r foo=3\n declare -rx bar=4\n ```\n \n ### Rationale:\n \n In most languages, declaration modifiers like `public`/`static`/`const` are keywords and you can apply multiple to any declaration.\n \n In shell scripting they are instead command names, and anything after them is an argument. This means that `readonly local foo` will create two readonly variables: `local`, and `foo`. Neither will be local.\n \n Instead, either use multiple commands, or use a single `declare` command with appropriate flags (`declare` will automatically make a variable local when invoked in a function, unless `-g` is passed to explicitly make it global).\n \n ### Exceptions:\n \n If you want to name your variable `local`, you can quote it as in `readonly \"local\"` to make your intention clear to ShellCheck and other humans.\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Command appears to be unreachable. Check usage (or ignore if invoked indirectly). [SC2317]"},{"from": "gpt", "value": "## Command appears to be unreachable. Check usage (or ignore if invoked indirectly).\n \n ### Problematic code:\n \n ```sh\n usage() {\n echo >&2 \"Usage: $0 -i input\"\n exit 1\n } \n if [ \"$1\" = \"--help\" ]\n then\n usage\n exit 0 # Unreachable\n fi\n ```\n \n ### Correct code:\n \n ```sh\n usage() {\n echo >&2 \"Usage: $0 -i input\"\n } \n if [ \"$1\" = \"--help\" ]\n then\n usage\n exit 0\n fi\n ```\n \n ### Rationale:\n \n The problematic code wanted to exit with success if the user explicitly asked for `--help`. However, since the `usage` function already had an `exit 1`, this statement could never run.\n \n One possible solution is to change `usage()` to only echo, and let callers be responsible for exiting.\n \n ### Exceptions:\n \n ShellCheck may incorrectly believe that code is unreachable if it's invoked by variable name or in a trap. In such a case, please [[Ignore]] the message. \n \n Note in particular that since unreachable commands may come in clusters, it's useful to use ShellCheck's filewide or functionwide ignore directives. A `disable` directive before a function ignores the entire function:\n \n ```\n #!/bin/bash\n ...\n # shellcheck disable=SC2317 # Don't warn about unreachable commands in this function\n start() {\n echo Starting\n /etc/init.d/foo start\n }\n \"$1\"\n exit 0\n ```\n \n A disable directive after the shebang, before any commands, will ignore the entire file:\n ```\n #!/bin/bash\n # Test script #1\n # shellcheck disable=SC2317 # Don't warn about unreachable commands in this file\n \n echo \"Temporarily disabled\"\n exit 0\n \n run-test1\n run-test2\n run-test3\n ```\n \n Defined functions are assumed to be reachable when the script ends (not exits) since another file may source and invoke them.\n \n ### More Problematic Code\n \n You have defined two functions in the same file you are sourcing whose names are the same but defined differently within their bodies. Then shellcheck will state that every line of the body of the earlier seen function definition will be unreachable which is how bash would operate when sourcing the file. It **unclear** what shellcheck would output if the earlier definition appeared in a difference file that was seen first. Apparently doing a quick test. It does **NOT** notice.\n \n \n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: This assignment is used again in this `declare`, but won't have taken effect. Use two `declare`s. [SC2318]"},{"from": "gpt", "value": "## This assignment is used again in this `declare`, but won't have taken effect. Use two `declare`s.\n \n (or `local`, `typeset`, `readonly`, `export`)\n \n ### Problematic code:\n \n ```sh\n declare -i first=$1 current=$first\n ```\n \n ### Correct code:\n \n ```sh\n declare -i first=$1\n declare -i current=$first\n ```\n \n ### Rationale:\n \n When assigning variables via a command, such as `declare`, `typeset`, `local` etc, the expansion of all arguments happen before all assignments. This means that you can't have a variable assigned and then referenced in the same command.\n \n In the example, if `$1` is 42, the arguments will first be expanded in the current environment into `-i first=42 current=`. They will then be passed to `declare` which will perform the assignments.\n \n To correctly set `current=$first` so that it uses the new value of `first`, use two separate commands as shown.\n \n Note that this only applies when assigning via commands, because arguments are always expanded before commands are invoked. If assigning without a command, as in `first=$1 current=$first`, it will work as expected.\n \n ### Exceptions:\n \n If you want to reference the value as it existed before the command, e.g. if swapping variables with `declare x=$y y=$x`, you can ignore this message. However, consider rewriting it anyways for the benefit of any humans reading the code.\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: This `$?` refers to a condition, not a command. Assign to a variable to avoid it being overwritten. [SC2319]"},{"from": "gpt", "value": "## This `$?` refers to a condition, not a command. Assign to a variable to avoid it being overwritten.\n \n ### Problematic code:\n \n ```sh\n mycommand\n if [ $? -ne 0 ] && [ $? -ne 14 ]\n then\n echo \"Command failed\"\n fi\n ```\n \n or\n \n ```sh\n mycommand\n [ $? -gt 0 ] && exit $?\n ```\n \n ### Correct code:\n \n ```sh\n mycommand\n ret=$?\n if [ $ret -ne 0 ] && [ $ret -ne 14 ]\n then\n echo \"Command failed\"\n fi\n ```\n \n or\n \n ```sh\n mycommand || exit $?\n ```\n \n \n ### Rationale:\n \n ShellCheck found a `$?` that always refers to a condition like `[ .. ]`, `[[ .. ]]`, or `test`.\n \n This most commonly happens when trying to inspect `$?` before doing something with it, such as inspecting it again or exiting with it, without realizing that any such inspection will also overwrite `$?`.\n \n In the first problematic example, `[ $? -ne 14 ]` will never be true because it only runs after `[ $? -ne 0 ]` has modified $? to be 0. The solution is to assign `$?` from `mycommand` to a variable so that the variable can be inspected repeatedly.\n \n In the second problematic example, `exit $?` will always `exit 0`, because it only runs if `[ $? -gt 0 ]` returns success and sets `$?` to 0. The solution could again be to assign `$?` to a variable first, or (as shown) use `mycommand || exit $?` as there is no condition to overwrite `$?`.\n \n ### Exceptions:\n \n None. Note that ShellCheck does not warn if the usage of `$?` after `[ .. ]` is unconditional, as in `[ -d dir ]; return $?`.\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: This `$?` refers to echo/printf, not a previous command. Assign to variable to avoid it being overwritten. [SC2320]"},{"from": "gpt", "value": "## This `$?` refers to echo/printf, not a previous command. Assign to variable to avoid it being overwritten.\n \n ### Problematic code:\n \n ```sh\n mycommand\n echo \"Command exited with $?\"\n if [ $? -ne 0 ]\n then\n echo \"Failed\"\n fi\n ```\n \n ### Correct code:\n \n ```sh\n mycommand\n ret=$?\n echo \"Command exited with $ret\"\n if [ $ret -ne 0 ]\n then\n echo \"Failed\"\n fi\n ```\n \n ### Rationale:\n \n ShellCheck found a `$?` that always refers to `echo` or `printf`. \n \n This most commonly happens when trying to show `$?` before doing something with it, without realizing that any such action will also overwrite `$?`.\n \n In the problematic example, `echo \"Command exited with $?\"` was intended to show the exit code before acting on it, but the act of showing `$?` also overwrote it, so the condition is always false. The solution is to assign `$?` to a variable first, so that it can be used repeatedly.\n \n ### Exceptions:\n \n If you intentionally refer to `echo` to get the result of a write, you can ignore this message. Alternatively, write it out as in `if echo $$ > \"$pidfile\"; then status=0; else status=1; fi`\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Array indices are already arithmetic contexts. Prefer removing the `$((` and `))`. [SC2321]"},{"from": "gpt", "value": "## Array indices are already arithmetic contexts. Prefer removing the `$((` and `))`.\n \n ### Problematic code:\n \n ```sh\n values[$((i+1))]=1\n ```\n \n ### Correct code:\n \n ```sh\n values[i+1]=1\n ```\n ### Rationale:\n \n In indexed arrays (but not associative ones), the array index is already an arithmetic context. There is no point or value in wrapping it in an additional, explicit `$((..))`.\n \n ### Exceptions:\n \n If ShellCheck has failed to realize that your array is associative, or if you for stylistic reasons prefer the redundancy, you can ignore this message. \n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: In arithmetic contexts, `((x))` is the same as `(x)`. Prefer only one layer of parentheses. [SC2322]"},{"from": "gpt", "value": "## In arithmetic contexts, `((x))` is the same as `(x)`. Prefer only one layer of parentheses.\n \n ### Problematic code:\n \n ```sh\n value=$(( ((offset + index)) * 512 )) \n ```\n \n ### Correct code:\n \n ```sh\n value=$(( (offset + index) * 512 ))\n ```\n ### Rationale:\n \n ShellCheck found doubly nested parentheses in an arithmetic expression. While the syntax for an arithmetic expansion is `$((..))`, this does not imply that parentheses in the expression should also be doubled. `(x)`, `((x))`, and `(((x)))` are all identical, so you might as well use only one layer of parentheses.\n \n ### Exceptions:\n \n This is a stylistic suggestion. If you prefer keeping both parentheses, you can [[ignore]] this message.\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: `a[(x)]` is the same as `a[x]`. Prefer not wrapping in additional parentheses. [SC2323]"},{"from": "gpt", "value": "## `a[(x)]` is the same as `a[x]`. Prefer not wrapping in additional parentheses.\n \n Similarly `$(( (x) ))` is the same as `$(( x ))`, `(( (x) ))` is the same as `(( x ))`.\n \n \n ### Problematic code:\n \n ```sh\n array[(x+1)]=val\n echo $(( (x+1) ))\n ```\n \n ### Correct code:\n \n ```sh\n array[x+1]=val\n echo $((x+1))\n ```\n \n ### Rationale:\n \n ShellCheck found an entire arithmetic expression wrapped in parentheses. This does not serve a purpose since the expression is already clearly delimited by the construct it's in, such as `array[..]=` or `$((..))` in the example.\n \n Note: ShellCheck does *not* warn about redundant parentheses in subexpressions, such as `(a*b)+c`. Feel free to use parentheses to clarify the order of operations any way you'd like. ShellCheck only emits this suggestion when the *entire* expression is wrapped *twice*.\n \n ### Exceptions:\n \n If you prefer having an extra layer of parentheses for stylistic reasons, you can [[ignore]] this message.\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: var+=1 will append, not increment. Use (( var += 1 )), declare -i var, or quote number to silence. [SC2324]"},{"from": "gpt", "value": "## var+=1 will append, not increment. Use (( var += 1 )), declare -i var, or quote number to silence.\n \n ### Problematic code:\n \n ```sh\n var=2 n=3\n var+=$n\n ```\n \n ### Correct code:\n \n In bash/ksh, use an `(( arithmetic context ))` \n \n ```sh\n (( var += n ))\n ```\n \n or declare the variable as an integer type:\n \n ```sh\n declare -i var=2\n n=4\n var+=$n\n ```\n \n For POSIX sh, use an `$((arithmetic expansion))`:\n \n ```sh\n var=$((var+n))\n ```\n \n \n ### Rationale:\n \n The problematic code attempts to add 2 and 3 to get 5.\n \n Instead, `+=` on a string variable will concatenate, so the result is 23.\n \n ### Exceptions:\n \n If you *do* want to concatenate a number, for example to append trailing zeroes, you can silence the warning by quoting the number:\n \n ```sh\n var+=\"000\"\n ```\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Multiple ! in front of pipelines are a bash/ksh extension. Use only 0 or 1. [SC2325]"},{"from": "gpt", "value": "## Multiple ! in front of pipelines are a bash/ksh extension. Use only 0 or 1.\n \n ### Problematic code:\n \n ```sh\n #!/bin/sh\n ! ! true\n ```\n \n ### Correct code:\n \n ```sh\n #!/bin/sh\n true\n ```\n ### Rationale:\n \n POSIX (and Dash) does not allow multiple `!` pipeline negations in a row. It's also logically unnecessary.\n \n Use either zero or one `!`.\n \n ### Exceptions:\n \n Scripts whose shebang declares it will run with Ksh and Bash will not trigger this warning.\n \n If you really want to negate multiple times on POSIX or Dash, e.g. to normalize exit codes to 0 or 1, use `cmd || false` or a command group:\n \n ```sh\n ! { ! true; } \n ```\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: ! is not allowed in the middle of pipelines. Use command group as in `cmd | { ! cmd; }` if necessary. [SC2326]"},{"from": "gpt", "value": "## ! is not allowed in the middle of pipelines. Use command group as in `cmd | { ! cmd; }` if necessary.\n \n ### Problematic code:\n \n ```sh\n cat | ! tee /dev/full\n ```\n \n ### Correct code:\n \n Either negate the entire pipeline (this is equivalent unless `pipefail` is set):\n \n ```sh\n ! cat | tee /dev/full\n ```\n \n Or use a command group to negate a single stage:\n \n ```sh\n cat | { ! tee /dev/full; }\n ```\n ### Rationale:\n \n [POSIX specifies](https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_09_02) that a status negation operator `!` is only used to negate the status of an entire pipeline, not individual stages.\n \n By default the status of a pipeline is that of the last command, so use `!` in front of the pipeline to negate as necessary.\n \n If you have set the option `pipefail` to OR the status of each stage together, and want to negate the status of only a single stage, you can use negate inside a `{ ! command group; }`.\n \n ### Exceptions:\n \n Ksh supports `!` in front of individual pipeline stages. ShellCheck does not warn when the shebang declares that the script will run with Ksh.\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: This command substitution will be empty because the command's output gets redirected away. [SC2327]"},{"from": "gpt", "value": "## This command substitution will be empty because the command's output gets redirected away.\n \n See companion warning [[SC2328]].\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: This redirection takes output away from the command substitution. [SC2328]"},{"from": "gpt", "value": "## This redirection takes output away from the command substitution.\n \n (and companion warning \"This command substitution will be empty because the command's output gets redirected away\" which points to the relevant command substitution)\n \n ### Problematic code:\n \n ```sh\n var=$(tr -d ':' < input.txt > output.txt)\n ```\n \n ### Correct code:\n \n ```sh\n # If the output should be captured INSTEAD OF being written to file\n var=$(tr -d ':' < input.txt)\n \n # If the output should be captured IN ADDITION to being written to file\n var=$(tr -d ':' < input.txt | tee output.txt)\n \n # If the output should NOT BE captured at all\n tr -d ':' < input.txt > output.txt\n ```\n \n ### Rationale:\n \n ShellCheck has found a command substitution (`$(..)`, `` `..` ``) that appears to never capture any output because the command's output is being redirected.\n \n Decide whether you want the output to be captured (by removing the redirection), to go into wherever it's redirected (by not running the command in a command substitution), or both (by using `tee` to copy the output to both file and stdout).\n \n ### Exceptions:\n \n None\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: This function is never invoked. Check usage (or ignored if invoked indirectly). [SC2329]"},{"from": "gpt", "value": "## This function is never invoked. Check usage (or ignored if invoked indirectly).\n \n ### Problematic code:\n \n ```sh\n #!/bin/sh\n f() {\n echo \"Hello World\"\n }\n exit\n ```\n \n ### Correct code:\n \n ```sh\n #!/bin/sh\n f() {\n echo \"Hello World\"\n }\n f\n exit\n ```\n ### Rationale:\n \n ShellCheck found a function that goes out of scope before it's ever invoked. Verify that the function is called. It could be misspelled, or its invocation could also be unreachable (as in `f() { ..; }; exit; f`).\n \n Note that if the example script did not end in `exit`, this warning would not be emitted. This is because the function could be invoked by another script that `source`s it.\n \n ### Exceptions:\n \n ShellCheck is currently bad at figuring out functions that are invoked via `trap`. In such cases, please [[ignore]] the message with a directive.\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: BusyBox `[[ .. ]]` does not support glob matching. Use a case statement. [SC2330]"},{"from": "gpt", "value": "## BusyBox `[[ .. ]]` does not support glob matching. Use a case statement.\n \n ### Problematic code:\n \n ```sh\n #!/bin/busybox sh\n if [[ $1 == https:* ]]\n then\n echo \"Using URL $1\"\n fi\n ```\n \n ### Correct code:\n \n ```sh\n #!/bin/busybox sh\n case \"$1\" in\n https:*)\n echo \"Using URL $1\" \n ;;\n esac\n ```\n \n ### Rationale:\n \n You are using `[[ .. ]]` in BusyBox `sh` to match against a glob pattern. This is supported in Bash and Ksh, but not in BusyBox.\n \n Rewrite the match to use a `case` statement instead.\n \n ### Exceptions:\n \n None.\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: For file existence, prefer standard -e over legacy -a. [SC2331]"},{"from": "gpt", "value": "## For file existence, prefer standard -e over legacy -a.\n \n ### Problematic code:\n \n ```sh\n if [ -a ~/.bash_aliases ]\n then\n source ~/.bash_aliases\n fi\n ```\n \n ### Correct code:\n \n ```sh\n if [ -e ~/.bash_aliases ]\n then\n source ~/.bash_aliases\n fi\n ```\n ### Rationale:\n \n The POSIX standard way to check whether a file exists is `[ -e file ]`.\n \n Bash and Ksh have historically allowed using `-a`, but this has no benefit and some potential downsides. For example, in Bash `[ -a file ]` is true when the file exists, but `[ ! -a file ]` is also true, and unconditionally so, because `-a` is treated as logical \"and\" between non-empty strings.\n \n Avoid the ambiguity entirely by always using the standard, portable `-e`.\n \n ### Exceptions:\n \n None\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: [ ! -o opt ] is always true because -o becomes logical OR. Use [[ ]] or ! [ -o opt ]. [SC2332]"},{"from": "gpt", "value": "## [ ! -o opt ] is always true because -o becomes logical OR. Use [[ ]] or ! [ -o opt ].\n \n Or \"`[ ! -a file ]` is always true because `-a` becomes logical AND. Use `-e` instead.\"\n \n \n ### Problematic code:\n \n ```sh\n if [ ! -o braceexpand ]\n then \n ..\n fi\n ```\n \n ### Correct code:\n \n ```sh\n if [[ ! -o braceexpand ]]\n then \n ..\n fi\n ```\n \n or \n \n ```sh\n if ! [ -o braceexpand ]\n then \n ..\n fi\n ```\n \n ### Rationale:\n \n Bash interprets `[ ! -o opt ]` as `[ \"!\" ] || [ \"opt\" ]` instead of negating the condition. As a result, the condition is always true.\n \n Avoid this by using `[[ ! -o opt ]]` or `! [ -o opt ]`.\n \n The same issue applies to `[ ! -a file ]`, but this is easier fixed using POSIX standard `[ ! -e file ]`.\n \n ### Exceptions:\n \n None.\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: In POSIX sh, process substitution is undefined. [SC3001]"},{"from": "gpt", "value": "## In POSIX sh, process substitution is undefined.\n \n (or \"In dash, ... is not supported.\" when using `dash`)\n \n ### Problematic code:\n \n ```sh\n #!/bin/sh\n while IFS= read -r n\n do\n sum=$((sum+n))\n done < <(program)\n ```\n \n ### Correct code:\n \n The easiest fix is to switch to a shell that does support process substitution, by changing the shebang to `#!/bin/bash` or `ksh`.\n \n ```sh\n #!/bin/bash\n while IFS= read -r n\n do\n sum=$((sum+n))\n done < <(program)\n ```\n \n Alternatively, process substitution can often be replaced with temporary files:\n \n ```sh\n #!/bin/sh\n tmp=\"$(mktemp)\"\n program > \"$tmp\"\n while IFS= read -r n\n do\n sum=$((sum+n))\n done < \"$tmp\"\n rm \"$tmp\"\n ```\n \n If streaming is important, the temporary file can be a named pipe, and the producer or consumer can be run as a background job.\n \n If the reading command accepts input from standard input, the process substitution can be replaced with a regular pipe:\n \n ```sh\n #!/bin/sh\n program | while IFS= read -r n\n do\n sum=$((sum+n))\n done\n ```\n \n ### Rationale:\n \n Process substitution is a ksh and bash extension. It does not work in sh or dash scripts.\n \n ### Exceptions:\n \n If you only intend to target shells that supports this feature, you can change\n the shebang to a shell that guarantees support, or [[ignore]] this warning.\n \n You can use `# shellcheck disable=SC3000-SC4000` to ignore all such compatibility\n warnings.\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: In POSIX sh, extglob is undefined. [SC3002]"},{"from": "gpt", "value": "## In POSIX sh, extglob is undefined.\n \n (or \"In dash, ... is not supported.\" when using `dash`)\n \n ### Problematic code:\n \n ```sh\n #!/bin/sh\n rm !(*.hs)\n ```\n \n ### Correct code:\n \n Either switch the shebang to a shell that does support extglob, like `bash` or `ksh`, or rewrite in terms of a loop with a `case` or `grep` match:\n \n ```sh\n #!/bin/sh\n for file in *\n do\n case \"$file\" in\n *.hs) true;;\n *) rm \"$file\" ;;\n esac\n done\n ```\n \n ### Rationale:\n \n Extglobs are extensions in bash and ksh, while your shebang says you're using `sh` or `dash`. \n \n ### Exceptions:\n \n If you only intend to target shells that supports this feature, you can change\n the shebang to a shell that guarantees support, or [[ignore]] this warning.\n \n You can use `# shellcheck disable=SC3000-SC4000` to ignore all such compatibility\n warnings.\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: In POSIX sh, `$'..'` is undefined. [SC3003]"},{"from": "gpt", "value": "## In POSIX sh, `$'..'` is undefined.\n \n ### Problematic code:\n \n ```sh\n #!/bin/sh\n IFS=$' \\t\\n'\n ```\n \n ### Correct code:\n \n ```sh\n #!/bin/sh\n # Note: \\n can not be last, or it will be stripped by $()\n IFS=$(printf ' \\n\\t')\n ```\n \n or \n \n ```sh\n #!/bin/sh\n # Trailing linefeed added literally\n IFS=\"$(printf ' \\t')\n \"\n ```\n \n or\n \n ```sh\n #!/bin/bash\n # Bash supports this\n IFS=$' \\t\\n'\n ```\n \n ### Rationale:\n \n ANSI-C quoting, `$'..'`, is a `bash` extension, which is not supported by POSIX `sh`.\n \n To ensure the script runs correctly on other systems, either switch to Bash, or rewrite it in a POSIX compatible way.\n \n This can generally done via `printf` as in the example. Be careful about strings with trailing linefeeds, as a `$(command substitution)` will strip them.\n \n ### Exceptions:\n \n None.\n \n ### Related resources:\n \n * StackOverflow: [Why does my bash code fail when I run it with sh?](https://stackoverflow.com/questions/15179446/why-does-my-bash-code-fail-when-i-run-it-with-sh)\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: In POSIX sh, $\"..\" is undefined [SC3004]"},{"from": "gpt", "value": "## In POSIX sh, $\"..\" is undefined\n \n ### Problematic code:\n \n ```sh\n printf $\"Hello, %s\\n\" \"$USER\"\n ```\n \n ### Correct code:\n \n ```sh\n # Check if gettext exists\n if ! type gettext > /dev/null 2>&1\n then\n # If not, create a dummy function that returns the input verbatim\n gettext() { printf '%s' \"$1\"; }\n fi\n \n # Use gettext to get a translated version of the string\n printf \"$(gettext 'Hello, %s\\n')\" \"$USER\"\n ```\n \n ### Rationale:\n \n Bash allows using `$\"...\"` to easily get a translated string according to the current locale. This is powered by the gettext infrastructure.\n \n Neither `$\"..\"` nor the gettext infrastructure or the `gettext` command is POSIX. A script targeting `sh` may choose to invoke `gettext` if the system has it (such as GNU or Solaris), or use the translated string verbatim if it doesn't (such as macOS or FreeBSD).\n \n ### Exceptions:\n \n None.\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: In POSIX sh, arithmetic for loops are undefined. [SC3005]"},{"from": "gpt", "value": "## In POSIX sh, arithmetic for loops are undefined.\n \n ### Problematic code:\n \n ```sh\n for ((i=0; i<10; i++))\n do \n echo \"$i\"\n done\n ```\n \n ### Correct code:\n \n ```sh\n i=0\n while [ \"$i\" -lt 10 ]\n do \n echo \"$i\"\n i=$((i+1))\n done\n ```\n \n ### Rationale:\n \n C-style arithmetic for loops are a Ksh/Bash feature that's not supported by POSIX sh or dash. Use a `while` loop with separate initialization and incrementing instead.\n \n ### Exceptions:\n \n None\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: In POSIX sh, standalone `((..))` is undefined. [SC3006]"},{"from": "gpt", "value": "## In POSIX sh, standalone `((..))` is undefined.\n \n ### Problematic code:\n \n ```sh\n variable=1\n if ((variable)); then\n echo variable is not zero\n fi\n ```\n \n ### Correct code:\n \n [`bash` supports standalone `((..))`](https://www.gnu.org/software/bash/manual/html_node/Conditional-Constructs.html#index-select) natively.\n \n For POSIX compliance, use\n \n ```sh\n variable=1\n if [ \"${variable}\" -ne 0 ]; then\n echo variable is not zero\n fi\n ```\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: In POSIX sh, `$[..]` in place of `$((..))` is undefined. [SC3007]"},{"from": "gpt", "value": "## In POSIX sh, `$[..]` in place of `$((..))` is undefined.\n \n ### Problematic code:\n \n ```sh\n var=$[1 + 2]\n ```\n \n ### Correct code:\n \n ```sh\n var=$((1 + 2))\n ```\n \n ### Rationale:\n \n Your script uses a shell feature not supported by the shebang. Either rewrite the script to be portable, or change the shebang to explicitly require a shell like Bash. In this case, `$[ .. ]` can easily be replaced by the POSIX standard arithmetic expansion `$(( .. ))`.\n \n ### Exceptions:\n \n None\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: In POSIX sh, select loops are undefined. [SC3008]"},{"from": "gpt", "value": "## In POSIX sh, select loops are undefined.\n \n ### Problematic code:\n \n ```sh\n #!/bin/sh\n echo \"Select file to show\"\n select input in *\n do\n ls -l \"$input\"\n done\n ```\n \n ### Correct code:\n \n Either switch to bash:\n \n ```sh\n #!/usr/bin/env bash\n echo \"Select file to show\"\n select input in *\n do\n ls -l \"$input\"\n done\n ```\n \n Or write your own menu.\n \n ### Rationale:\n \n Your script uses a shell feature not supported by the shebang. Either rewrite the script to be portable, or change the shebang to explicitly require a shell like Bash. There is no simple substitution for a `select` loop, so either write your own using compatible constructs like `for` loops, or switch to a shell that supports them.\n \n ### Exceptions:\n \n None\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: In POSIX `sh`, brace expansion is undefined. [SC3009]"},{"from": "gpt", "value": "## In POSIX `sh`, brace expansion is undefined.\n \n ### Problematic code:\n \n ```sh\n #!/bin/sh\n \n for i in {1..5}; do ...\n ```\n \n Here, `$i` expands to `{1..5}`. It does **not** expand to the sequence `1 2 3 4 5`\n \n ### Correct code:\n \n ```sh\n #!/bin/sh\n i=1\n # while $i ≤ 5 ...\n while [ \"${i}\" -le 5 ]; do ...\n \n # something that will occur 5 times\n \n i=$((i + 1))\n done\n ```\n \n You can also use the `seq` command, e.g. `seq 1 5`, but `seq` is not a POSIX utility.\n \n ### Rationale:\n \n ### Exceptions:\n \n None\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: In POSIX sh, `[[ ]]` is undefined. [SC3010]"},{"from": "gpt", "value": "## In POSIX sh, `[[ ]]` is undefined.\n \n POSIX sh uses `[ ]` and `test` instead. To see the limitations/differences, view http://mywiki.wooledge.org/BashFAQ/031 \n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: In POSIX sh, here-strings are undefined. [SC3011]"},{"from": "gpt", "value": "## In POSIX sh, here-strings are undefined.\n \n ### Problematic code:\n \n ```sh\n #!/bin/sh\n wc <<< \"$1\"\n ```\n \n ### Correct code:\n \n ```sh\n #!/bin/sh\n wc << EOF\n $1\n EOF\n ```\n \n ### Rationale:\n \n Your script uses a shell feature not supported by the shebang. Either rewrite the script to be portable, or change the shebang to explicitly require a shell like Bash. In this specific case, the here-string can be replaced by a single-line here document as shown.\n \n ### Exceptions:\n \n None\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: In POSIX sh, lexicographical `\\<` is undefined. [SC3012]"},{"from": "gpt", "value": "## In POSIX sh, lexicographical `\\<` is undefined.\n \n ### Problematic code:\n \n ```sh\n #!/bin/sh\n x=\"aardvark\"\n y=\"zebra\"\n if [ $x \\< $y ]\n then\n echo \"$x comes before $y in the dictionary\"\n fi\n ```\n \n ### Correct code:\n \n First, make sure you wanted a lexicographical comparison (aka dictionary order), and not a numerical comparison.\n \n Then to compare as string, you can use `expr` and make sure that the strings are not interpreted numerically by adding some non-numerical data to them. Here, an apostrophe is prepended:\n \n ```\n #!/bin/sh\n x=\"aardvark\"\n y=\"zebra\"\n if expr \"'$x\" \\< \"'$y\" > /dev/null \n then\n echo \"$x comes before $y in the dictionary\"\n fi\n ```\n \n ### Rationale:\n \n The `test` binary operators `>`, `\\>`, `<`, and `\\<` are not part of POSIX and not guaranteed to be supported in scripts targeting `sh`.\n \n The `expr` functionality is specified by POSIX.\n \n ### Exceptions:\n \n If you know your `sh` will be e.g. `dash`, consider explicitly using `#!/bin/dash`. \n \n ### Related resources:\n \n * [Greg's Wiki - Bashism - Conditionals](https://mywiki.wooledge.org/Bashism#Conditionals)\n * POSIX: [test](https://pubs.opengroup.org/onlinepubs/9699919799/utilities/test.html#tag_20_128), [expr](https://pubs.opengroup.org/onlinepubs/9699919799/utilities/expr.html)\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: In POSIX sh, `-nt` is undefined. [SC3013]"},{"from": "gpt", "value": "## In POSIX sh, `-nt` is undefined.\n \n ### Problematic code:\n \n ```sh\n #!/bin/sh\n if [ Foo.java -nt Foo.class ]\n then\n javac Foo.java\n fi\n ```\n \n ### Correct code:\n \n The easiest fix is to switch to a shell that *does* support `-nt`, like bash:\n \n ```sh\n #!/bin/bash\n if [ Foo.java -nt Foo.class ]\n then\n javac Foo.java\n fi\n ```\n \n Otherwise, `find` can be used:\n \n ```sh\n #!/bin/sh\n if [ -n \"$(find Foo.java -newer Foo.class)\" ]\n then\n javac Foo.java\n fi\n ```\n \n ### Rationale:\n \n `test -nt` is an extension in ksh, bash and dash, but it is [not specified by POSIX](https://pubs.opengroup.org/onlinepubs/9699919799/utilities/test.html).\n \n ### Exceptions:\n \n If you only intend to target shells that supports this feature, you can change\n the shebang to a shell that guarantees support, or [[ignore]] this warning.\n \n You can use `# shellcheck disable=SC3000-SC4000` to ignore all such compatibility\n warnings.\n \n ### Related resources:\n \n * Greg's Wiki\n * [BashFAQ #3: How can I sort or compare files based on some metadata attribute (newest / oldest modification time, size, etc)?](https://mywiki.wooledge.org/BashFAQ/003)\n * [Bashism - Conditionals](https://mywiki.wooledge.org/Bashism#Conditionals)\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: In POSIX sh, `==` in place of `=` is undefined. [SC3014]"},{"from": "gpt", "value": "## In POSIX sh, `==` in place of `=` is undefined.\n \n (or \"In dash, ... is not supported.\" when using `dash`)\n \n ### Problematic code:\n \n ```sh\n #!/bin/sh\n if [ $1 == \"-n\" ]\n then\n dry_run=1\n fi\n ```\n \n ### Correct code:\n \n ```sh\n #!/bin/sh\n if [ $1 = \"-n\" ]\n then\n dry_run=1\n fi\n ```\n \n ### Rationale:\n \n `==` is used for equality comparison in C-like languages, and is also supported by `bash` and `ksh` in `[ .. ]` and `test` expressions.\n \n `sh` and `dash` only supports `=` for equality comparison, so use that instead.\n \n ### Exceptions:\n \n If you only intend to target shells that supports this feature, you can change\n the shebang to a shell that guarantees support, or [[ignore]] this warning.\n \n You can use `# shellcheck disable=SC3000-SC4000` to ignore all such compatibility\n warnings.\n \n ### Related resources:\n \n * Greg's Wiki\n * [Bash Pitfall #20: `[ bar == \"$foo\" ]`](https://mywiki.wooledge.org/BashPitfalls#pf20)\n * [Bashism - Conditionals](https://mywiki.wooledge.org/Bashism#Conditionals)\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: In POSIX sh, `=~` regex matching is undefined. [SC3015]"},{"from": "gpt", "value": "## In POSIX sh, `=~` regex matching is undefined.\n \n ### Problematic code:\n \n ```sh\n #!/bin/sh\n if [ \"$var\" =~ foo[0-9]+ ]; then\n echo matched\n fi\n ```\n \n ### Correct code:\n \n ```sh\n #!/bin/sh\n # Use the x-hack to handle strings like '('.\n if expr \"X$var\" : 'X.*foo[0-9]\\{1,\\}' >/dev/null; then\n echo matched\n fi\n ```\n or\n ```sh\n #!/bin/sh\n case $var in\n *foo[0-9]*)\n echo matched\n ;;\n esac\n ```\n \n ### Rationale:\n \n You are using `=~` in a script declared to be compatible with POSIX sh or Dash, but `=~` is [not specified by POSIX](https://pubs.opengroup.org/onlinepubs/9699919799/utilities/test.html) and is unlikely to work outside `[[ ]]` in Bash and Ksh.\n \n Use [`expr`'s `:` operator](https://pubs.opengroup.org/onlinepubs/9699919799/utilities/expr.html#tag_20_42_13_01) instead. It may be necessary to revise the regular expression because POSIX `expr` uses [basic regular expressions](https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap09.html#tag_09_03) anchored to the beginning of the string, as opposed to the unanchored [extended regular expressions](https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap09.html#tag_09_04) used by `[[ str =~ re ]]` in Bash and Ksh.\n \n Alternately, use `case` if the matching can be done with [shell patterns](https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_13) instead of regular expressions. This avoids the need for an external utility.\n \n ### Exceptions:\n \n None\n \n ### Related resources:\n \n * [Greg's Wiki - BashFAQ #41: How do I determine whether a variable contains a substring?](https://mywiki.wooledge.org/BashFAQ/041)\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: In POSIX sh, unary `-v` (in place of `[ -n \"${var+x}\" ]`) is undefined. [SC3016]"},{"from": "gpt", "value": "## In POSIX sh, unary `-v` (in place of `[ -n \"${var+x}\" ]`) is undefined.\n \n ### Problematic code:\n \n ```sh\n #!/bin/sh\n if [ -v STY ]\n then\n echo \"STY is set, you are using screen\"\n fi\n ```\n \n ### Correct code:\n \n Either switch to bash or ksh, or use:\n ```sh\n #!/bin/sh\n if [ -n \"${STY+x}\" ]\n then\n echo \"STY is set, you are using screen\"\n fi\n ```\n \n ### Rationale:\n \n Your script uses a shell feature not supported by the shebang. Either rewrite the script to be portable, or change the shebang to explicitly require a shell like Bash.\n \n In this case, `[ -v variable ]`, which checks if a variable is set, is [not specified by POSIX](https://pubs.opengroup.org/onlinepubs/9699919799/utilities/test.html). It can be replaced with the portable `[ -n \"${variable+x}\" ]`, which uses the \"alternative value if set\" [parameter expansion](https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_02) syntax to accomplish the same thing.\n \n ### Exceptions:\n \n None\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: In POSIX sh, unary `-a` in place of `-e` is undefined. [SC3017]"},{"from": "gpt", "value": "## In POSIX sh, unary `-a` in place of `-e` is undefined.\n \n (or \"In dash, ... is not supported.\" when using `dash`)\n \n ### Problematic code:\n \n ```sh\n #!/bin/sh\n if [ -a file.txt ]\n then\n echo \"file.txt exists\"\n fi\n ```\n \n ### Correct code:\n \n ```sh\n #!/bin/sh\n if [ -e file.txt ]\n then\n echo \"file.txt exists\"\n fi\n ```\n \n ### Rationale:\n \n `-a` was used in some shells to check for the existence of a file, but the POSIX standard and better supported equivalent is `-e`.\n \n ### Exceptions:\n \n If you only intend to target shells that supports this feature, you can change\n the shebang to a shell that guarantees support, or [[ignore]] this warning.\n \n You can use `# shellcheck disable=SC3000-SC4000` to ignore all such compatibility\n warnings.\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: In POSIX sh, `++` is undefined. [SC3018]"},{"from": "gpt", "value": "## In POSIX sh, `++` is undefined.\n \n (or \"In dash, ... is not supported.\" when using `dash`)\n \n ### Problematic code:\n \n ```sh\n #!/bin/sh\n i=1\n echo \"$((i++))\"\n ```\n \n ### Correct code:\n \n Write out the increment/decrement operation explicitly:\n \n ```sh\n #!/bin/sh\n i=1\n echo \"$i\"\n i=$((i+1))\n ```\n \n ### Rationale:\n \n Prefix and postfix increment and decrement are extensions in bash and ksh. They're not supported in dash or POSIX sh, which is what your shebang says you're using.\n \n ### Exceptions:\n \n If you only intend to target shells that supports this feature, you can change\n the shebang to a shell that guarantees support, or [[ignore]] this warning.\n \n You can use `# shellcheck disable=SC3000-SC4000` to ignore all such compatibility\n warnings.\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: In POSIX sh, exponentials are undefined. [SC3019]"},{"from": "gpt", "value": "## In POSIX sh, exponentials are undefined.\n \n ### Problematic code:\n \n ShellCheck noticed you're using `**`-notation with two asterisks to obtain an exponent's value. Some examples:\n \n ```sh\n #!/bin/sh\n echo $((2 ** 3)) # Using `**` for an exponent is undefined in POSIX sh.\n ```\n \n ### Correct code:\n \n Other possibilities exist:\n ```sh\n #!/bin/sh\n echo $((2 * 2 * 2)) # equivalent to `bash`'s `echo $((2 ** 3))`\n echo '2 ^ 3' | bc # piping the formula to `bc` to parse the output https://stackoverflow.com/a/13111995\n printf '2 ^ 3\\n' | bc # piping using `printf` (newline `\\n` is mandatory)\n ```\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: In POSIX sh, `&>` is undefined. [SC3020]"},{"from": "gpt", "value": "## In POSIX sh, `&>` is undefined.\n \n (or \"In dash, ... is not supported.\" when using `dash`)\n \n ### Problematic code:\n \n ```sh\n #!/bin/sh\n ssh host cmd &> log\n ```\n \n ### Correct code:\n \n Use the long form instead of the shorthand:\n \n ```sh\n #!/bin/sh\n ssh host cmd > log 2>&1\n ```\n \n ### Rationale:\n \n `&>` is a bash and ksh extension for redirecting both stdout and stderr. In dash and POSIX sh, use `2>&1` explicitly.\n \n ### Exceptions:\n \n If you only intend to target shells that supports this feature, you can change\n the shebang to a shell that guarantees support, or [[ignore]] this warning.\n \n You can use `# shellcheck disable=SC3000-SC4000` to ignore all such compatibility\n warnings.\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: In POSIX sh, `>& filename` (as opposed to `>& fd`) is undefined. [SC3021]"},{"from": "gpt", "value": "## In POSIX sh, `>& filename` (as opposed to `>& fd`) is undefined.\n \n Note: ShellCheck 0.8.0 and below would trigger this warning on the perfectly POSIX compatible construct `>& fd`. If you are using `>&` to copy an integer file descriptor, please ignore this warning.\n \n ### Problematic code:\n \n ```sh\n # Writing to a filename\n mycommand >& log.txt\n ```\n \n ### Correct code:\n \n ```sh\n mycommand > log.txt 2>&1\n ```\n \n The following construct is also fine, as it uses an integer file descriptor instead of a filename:\n \n ```sh\n fd=3\n mycommand >& $fd\n ```\n \n ### Rationale:\n \n There are two forms of the `>&` file descriptor operator:\n \n * `>& integer` such as `>& 3` is a POSIX compatible synonym for `1>&3`\n * `>& filename` such as `>& log.txt` is a Bash specific synonym for `> log.txt 2>&1`\n \n If (and only if) you are using the latter form, write it out as shown in the correct example to ensure portability.\n \n ### Exceptions:\n \n ShellCheck 0.8.0 and below incorrectly emits this warning for constructs like `>& $var`, even though this would be POSIX compatible when `$var` is an integer. In such cases, please ignore this warning.\n \n ### Related resources:\n \n * [Shellcheck issue #2520](https://github.com/koalaman/shellcheck/issues/2520)\n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: In POSIX sh, named file descriptors is undefined. [SC3022]"},{"from": "gpt", "value": "## In POSIX sh, named file descriptors is undefined.\n \n (or \"In dash, ... is not supported.\" when using `dash`)\n \n ### Problematic code:\n \n ```sh\n exec {n}> \"$output\"\n echo \"Your fd is $n\"\n ```\n \n ### Correct code:\n \n There is no simple, mechanical alternative for POSIX sh, but you can either switch to a shell that does support this (like `bash`), or hard code (or `eval`) a specific file descriptor. \n \n ### Rationale:\n \n The syntax for opening an arbitrary file descriptor and assigning it to a variable for later use is a `bash` and `ksh` extension. It does not work on POSIX sh or `dash`.\n \n ### Exceptions:\n \n None\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: In POSIX sh, FDs outside 0-9 are undefined. [SC3023]"},{"from": "gpt", "value": "## In POSIX sh, FDs outside 0-9 are undefined.\n \n (or \"In dash, ... are not supported.\" when using `dash`)\n \n ### Problematic code:\n \n ```sh\n # Open FD #10 for writing\n exec 10> file\n ```\n \n ### Correct code:\n \n Either rewrite the script to only use FDs in the valid range, or switch to a shell that allows a larger range like `bash` or `ksh`.\n \n ### Rationale:\n \n The shell grammar is only required to recognize a single digit before redirections to set the file descriptor, which limits the portable range to 0-9.\n \n ### Exceptions:\n \n None.\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: In POSIX sh, `+=` is undefined. [SC3024]"},{"from": "gpt", "value": "## In POSIX sh, `+=` is undefined.\n \n (or \"In dash, ... is not supported.\" when using `dash`)\n \n ### Problematic code:\n \n ```sh\n var=\"Hello \"\n var+=\"World\"\n ```\n \n ### Correct code:\n \n ```sh\n var=\"Hello \"\n var=\"${var}World\"\n ```\n \n ### Rationale:\n \n Using `+=` to concatenate to an existing variable is a ksh/bash extension. For POSIX sh or dash, write out the full expression. Be careful to use braces if the text you append could be confused for a variable (as in the example, to avoid `$varWorld` being interpreted as `${varWorld}`) \n \n ### Exceptions:\n \n None.\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: In POSIX sh, `/dev/{tcp,udp}` is undefined. [SC3025]"},{"from": "gpt", "value": "## In POSIX sh, `/dev/{tcp,udp}` is undefined.\n \n (or \"In dash, ... is not supported.\" when using `dash`)\n \n ### Problematic code:\n \n ```sh\n echo foo > /dev/tcp/myhost/1234\n ```\n \n ### Correct code:\n \n Rewrite using a tool like netcat (`nc`):\n \n ```sh\n echo foo | nc myhost 1234\n ```\n \n ### Rationale:\n \n `/dev/tcp/$host/$port` and `/dev/udp/$host/$port` are recognized in redirections by bash and ksh, and a socket connection is made instead of opening a file. They do not physically exist in `/dev`.\n \n POSIX sh and dash do not support this, so any such code should be rewritten to use a socket tool explicitly. The obvious candidate is netcat aka `nc`. \n \n ### Exceptions:\n \n None\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: In POSIX sh, `^` in place of `!` in glob bracket expressions is undefined. [SC3026]"},{"from": "gpt", "value": "## In POSIX sh, `^` in place of `!` in glob bracket expressions is undefined.\n \n ### Problematic code:\n \n ```sh\n echo foo-[^0]*.jpg\n ```\n \n ### Correct code:\n \n ```sh\n echo foo-[!0]*.jpg\n ```\n or if the intention is to match `^` literally then either do not put it immediately after `[` or quote it by backslash `\\`\n ```sh\n echo foo-[0^]*.jpg foo-[\\^0]*.jpg\n ```\n \n ### Rationale:\n \n `[^c]` is frequently used in most regular expression variants to mean \"any character except `c`\". Ksh and Bash adopted it for globs as well.\n \n However, strictly speaking, the only range complement syntax guaranteed to be supported across shells is `[!c]`. POSIX explicitly states that behavior of `[^c]` is unspecified. Dash used to support `[^c]` when compiled with `fnmatch` and `glob` from glibc, but it was considered as a [bug](https://lore.kernel.org/dash/09fd70edcf08c75b4f9f2e158e3e6c0832d35d90.camel@scientia.org/t/#u) and fixed in version 0.5.12. Busybox has a similar [bug 14516](https://bugs.busybox.net/show_bug.cgi?id=14516).\n \n In zsh interactive sessions `echo foo-[!0]*.jpg` may cause `zsh: event not found: 0` error due to attempt of history expansion. BASH however suppresses history expansion when `!` is first character in square brackets.\n \n Discrepancy of negation syntax in regular expressions and shell pattern matching appeared in early UNIX versions. Pipeline syntax in shells had not settled yet, some terminals had no `|` key, so `^` was used there. That is why in some shells exclamation mark `!` was chosen instead of circumflex (caret) `^` symbol for negation in globs. For more details related to shell history see [\"The `^` `=` `|` ?\" thread](https://inbox.vuxu.org/tuhs/20030126014003.GA3818@sydney.worldwide.lemis.com/T/#u) in the Unix Heritage Society mailing list or [Sven Mascheck. The Traditional Bourne Shell Family. History and Development](https://www.in-ulm.de/~mascheck/bourne/) page.\n \n ### Exceptions:\n \n If you only intend to target shells that supports this feature, you can change\n the shebang to a shell that guarantees support, or [[ignore]] this warning.\n Or just rewrite it to be on the technically correct side.\n \n ### Related resources:\n \n * [2.13.1 Patterns Matching a Single Character](https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_13_01) in the Shell and Utilities (XCU) volume of POSIX.1-2017.\n * [0001558: require `[^...]` in addition to `[!...]` for bracket expression negation](https://www.austingroupbugs.net/view.php?id=1558) POSIX enhancement request was rejected.\n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: In POSIX sh, VARIABLE is undefined. [SC3028]"},{"from": "gpt", "value": "## In POSIX sh, VARIABLE is undefined.\n \n (or \"In dash, ... is not supported.\" when using `dash`)\n \n ### Problematic code:\n \n ```sh\n #!/bin/sh\n echo \"$HOSTNAME $UID $RANDOM\"\n ```\n \n ### Correct code:\n \n Either switch to a shell like `bash` that supports the special variable you're trying to use, or use an external command to get the information you want:\n \n ```sh\n #!/bin/sh\n echo \"$(hostname) $(id -u) $(awk 'BEGIN { srand(); print int(rand()*32768) }' /dev/null)\"\n ```\n \n ### Rationale:\n \n The variable you are attempting to use is a special variable in bash or ksh. To get the same information from `dash` or POSIX `sh`, use an external command instead.\n \n For `PIPESTATUS`, the pipeline can be instrumented to record the exit value of each command:\n \n ```sh\n { cmd0; echo $? > status0; } | { cmd1; echo $? > status1; } | cmd2\n ```\n \n ### Exceptions:\n \n If you only intend to target shells that support this feature, you can change\n the shebang to a shell that guarantees support, or [[ignore]] this warning.\n \n You can use `# shellcheck disable=SC3000-SC4000` to ignore all such compatibility\n warnings.\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: In POSIX sh, `|&` in place of `2>&1 |` is undefined. [SC3029]"},{"from": "gpt", "value": "## In POSIX sh, `|&` in place of `2>&1 |` is undefined.\n \n ### Problematic code:\n \n ```sh\n #!/bin/sh\n make |& tee ~/log\n ```\n \n ### Correct code:\n \n Either switch to bash:\n \n ```sh\n #!/bin/sh\n make 2>&1 | tee ~/log\n ```\n \n ### Rationale:\n \n Your script uses a shell feature not supported by the shebang. Either rewrite the script to be portable, or change the shebang to explicitly require a shell like Bash.\n \n In this case, the non-portable shorthand `|&` to pipe both stdout and stderr can be easily replaced with its written out form `2>&1 |` as shown.\n \n ### Exceptions:\n \n None\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: In POSIX sh, arrays are undefined. [SC3030]"},{"from": "gpt", "value": "## In POSIX sh, arrays are undefined.\n \n ### Problematic code:\n \n ```sh\n #!/bin/sh\n x=( foo bar \"Hello World\" )\n for word in \"${x[@]}\"\n do\n touch \"$word.dat\"\n done\n ```\n \n ### Correct code:\n \n Consider switching to a shell that does support arrays, such as `bash` or `ksh`, by changing the shebang.\n \n Alternatively, if you only need a single array at a time, you may be able to rewrite to use the positional parameters:\n \n ```sh\n set -- foo bar \"Hello World\"\n for word in \"$@\"\n do\n touch \"$word.dat\"\n done\n ```\n \n or strings with carefully chosen delimiters:\n \n ```sh\n x='foo\n bar\n Hello World\n '\n \n printf '%s' \"$x\" |\n while IFS='' read -r word\n do\n touch \"$word.dat\"\n done\n ```\n \n ### Rationale:\n \n Arrays are specific to Bash and Ksh, but you are using them in a script declared to run with `sh` or `dash`. These shells do not support arrays at all. You should either switch to Bash/Ksh, or rewrite the script to not use arrays.\n \n There are no great replacements, especially none that can be mechanically applied, but using the positional parameters or a delimited string works in many cases, as shown in the examples. \n \n ### Exceptions:\n \n None.\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: In POSIX sh, redirecting from/to globs is undefined. [SC3031]"},{"from": "gpt", "value": "## In POSIX sh, redirecting from/to globs is undefined.\n \n (or \"In dash, ... is not supported.\" when using `dash`)\n \n ### Problematic code:\n \n ```sh\n #!/bin/sh\n date > /tmp/log*.txt\n ```\n \n ### Correct code:\n \n To redirect from/to the only match of a glob, expand the glob first:\n \n ```sh\n #!/bin/sh\n set -- /tmp/log*.txt\n # PS: This is a good place to verify that there was exactly one match\n date > \"$1\"\n ```\n \n Alternatively, use a loop to redirect from/to all if that was the intention.\n \n ### Rationale:\n \n Shells differ in whether (and how) they do pathname expansion on names in redirections. Avoid the issue by expanding the glob yourself. \n \n ### Exceptions:\n \n If you only intend to target shells that supports this feature, you can change\n the shebang to a shell that guarantees support, or [[ignore]] this warning.\n \n You can use `# shellcheck disable=SC3000-SC4000` to ignore all such compatibility\n warnings.\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: In POSIX sh, coproc is undefined. [SC3032]"},{"from": "gpt", "value": "## In POSIX sh, coproc is undefined.\n \n ### Problematic code:\n \n ```sh\n #!/bin/sh\n coproc nc shellcheck.net 80\n ```\n \n ### Correct code:\n \n Either switch to Bash:\n \n ```sh\n #!/usr/bin/env bash\n coproc nc shellcheck.net 80\n ```\n \n or try to write your script in a POSIX compatible way using named pipes.\n \n ### Rationale:\n \n Your script uses a shell feature not supported by the shebang. Either rewrite the script to be portable, or change the shebang to explicitly require a shell like Bash.\n \n There is no simple substitution for a coproc, though many use cases can be rewritten via redirection to named pipes (`mkfifo`).\n \n ### Exceptions:\n \n None\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: In POSIX sh, naming functions outside [a-zA-Z_][a-zA-Z0-9_]* is undefined. [SC3033]"},{"from": "gpt", "value": "## In POSIX sh, naming functions outside [a-zA-Z_][a-zA-Z0-9_]* is undefined.\n \n ### Problematic code:\n \n ```sh\n #!/bin/sh\n run-tests() {\n make test\n }\n ```\n \n ### Correct code:\n \n ```sh\n #!/bin/sh\n run_tests() {\n make test\n }\n ```\n \n ### Rationale:\n \n Your script uses a shell feature not supported by the shebang. Either rewrite the script to be portable, or change the shebang to explicitly require a shell like Bash.\n \n In this case, you can rename your functions to follow the same naming requirements as variables, as these are the only names guaranteed to be valid function names in POSIX.\n \n ### Exceptions:\n \n None\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: In POSIX sh, `$(\n \n ### Rationale:\n \n In a script declared to run with `sh` or `dash`, ShellCheck found `set -o` used with an option that is not defined by POSIX. The option may not be supported by these shells.\n \n ### Exceptions:\n \n If the script has already inspected the current shell and determined the option is available, you can [[ignore]] this message.\n \n ### `pipefail`\n \n #### Problematic code:\n \n ```sh\n #!/bin/sh\n set -o pipefail\n if cmd1 | cmd2 | cmd3\n then\n echo \"Success\"\n fi\n ```\n \n #### Correct code:\n \n ```sh\n fail=\"$(mktemp)\"\n if { cmd1 || echo > \"$fail\"; } |\n { cmd2 || echo > \"$fail\"; } |\n cmd3 && [ ! -s \"$fail\" ]\n then\n echo \"Success\"\n fi\n rm \"$fail\"\n ```\n \n Each stage in the pipeline such as `cmd1` can be rewritten as `{ cmd1 || echo > file; }` which will behave as before but now also write the exit code into `file` if the command fails.\n \n If the file has been written to when the pipeline is done, it means one of the commands failed. This is demonstrated in the correct example.\n \n This can obviously be extended with e.g. `echo \"cmd1=$?\" >> file` if the particular exit codes for particular commands are desired.\n \n If `pipefail` or other options are used only as a sanity check, another option is to try the setting in a subshell and only apply it in the main shell if successful. This will set the flag on platforms where `sh` is linked to `ash`, `busybox`, or `bash`, but do nothing if `sh` is `dash`.\n \n ```sh\n # Set pipefail if it works in a subshell, disregard if unsupported\n # shellcheck disable=SC3040\n (set -o pipefail 2> /dev/null) && set -o pipefail\n ```\n \n Alternatively, switch to a shell that supports `pipefail`, such as Bash.\n \n ### Related resources:\n \n * [POSIX.1-2017 - Shell Command Language - `set`](https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set)\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: In POSIX sh, set flag `-E` is undefined [SC3041]"},{"from": "gpt", "value": "## In POSIX sh, set flag `-E` is undefined\n \n (or any other option)\n \n ### Problematic code:\n \n ```sh\n #!/bin/sh\n set -EB\n ```\n \n ### Correct code:\n \n Switch to a shell that supports these options, such as Bash:\n \n ```sh\n #!/bin/bash\n set -EB\n ```\n \n ### Rationale:\n \n Your script uses a shell feature not supported by the shebang. Either rewrite the script to be portable, or change the shebang to explicitly require a shell like Bash.\n \n Most shell specific `set` flags are hard to emulate in POSIX, so use your best judgement as to whether you can make do without them, or if you should require a shell that supports them.\n \n ### Exceptions:\n \n None\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: In POSIX sh, set flag `--default` is undefined [SC3042]"},{"from": "gpt", "value": "## In POSIX sh, set flag `--default` is undefined\n \n (or any other option)\n \n ### Problematic code:\n \n ```sh\n #!/bin/ksh\n set --default\n ```\n \n ### Correct code:\n \n Switch to a shell that supports these options, such as Ksh:\n \n ```sh\n #!/bin/ksh\n set --default\n ```\n \n ### Rationale:\n \n Your script uses a shell feature not supported by the shebang. Either rewrite the script to be portable, or change the shebang to explicitly require a shell like Ksh.\n \n Most shell specific `set` flags are hard to emulate in POSIX, so use your best judgement as to whether you can make do without them, or if you should require a shell that supports them.\n \n ### Exceptions:\n \n None\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: In POSIX sh, `local` is undefined. [SC3043]"},{"from": "gpt", "value": "## In POSIX sh, `local` is undefined.\n \n ### Problematic code:\n \n ```sh\n myfunc() {\n local i=0\n ..\n }\n ```\n \n ### Correct code:\n \n In POSIX sh, you can adopt some convention to avoid accidentally overwriting variables names, e.g. prefixing with the function name:\n \n ```sh\n myfunc() {\n _myfunc_i=0\n ..\n }\n ```\n \n ### Rationale:\n \n `local` is supported in many shells, including bash, ksh, dash, and BusyBox ash. However, [it is not specified by POSIX](https://austingroupbugs.net/view.php?id=767).\n \n ### Exceptions:\n \n Since quite a lot of real world shells support this feature, you may decide to [[ignore]] the warning.\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: In POSIX sh, `declare` is undefined. [SC3044]"},{"from": "gpt", "value": "## In POSIX sh, `declare` is undefined.\n \n ### Problematic code:\n \n ```sh\n #!/bin/sh\n declare var=\"value\"\n ```\n \n or\n \n ```sh\n #!/bin/sh\n declare -r readonly\n ```\n \n or\n \n ```sh\n #!/bin/sh\n declare ...\n ```\n \n ### Correct code:\n \n If assigning a simple variable outside of a function, skip `declare` all together:\n \n ```sh\n var=\"value\"\n ```\n \n If declaring a variable read-only:\n ```\n var=value\n readonly var\n ```\n \n If you are unable to find a suitable replacement, consider switching to a shell that supports `declare`:\n \n ```sh\n #!/bin/bash\n declare ...\n ```\n \n Indexed arrays, associative arrays, local variables, namerefs, and integer variables are not supported in POSIX sh. Either write around them, or switch to a shell that supports them.\n \n ### Rationale:\n \n The `declare` command is non-standard, and most of its functionality is not available across shells.\n \n Either find a POSIX replacement, or switch to a shell that is guaranteed to support them.\n \n \n ### Exceptions:\n \n If your `declare` command is guarded by a check of the shell version, such as inspecting `$BASH_VERSION`, you can ignore this message.\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: In POSIX sh, some-command-with-flag is undefined. [SC3045]"},{"from": "gpt", "value": "## In POSIX sh, some-command-with-flag is undefined.\n \n (or \"In dash, ... is not supported.\" when using `dash`)\n \n ### Problematic code:\n \n ShellCheck has noticed you're using flags for commands that don't necessarily support them. Some examples:\n \n ```sh\n #!/bin/sh\n read -e # Using libreadline\n export -f # Exporting functions\n ulimit -v # Setting vspace limits\n wait -n # Waiting for a single process\n ```\n \n ### Correct code:\n \n There are generally no simple rewrites. The easiest solution is instead to change the shebang and switch to a shell that *does* support the features you want, such as `bash`.\n \n Alternatively, look up how to do what you want to do in POSIX sh.\n \n ### Rationale:\n \n External commands (`grep`, `ls`, `find`) invoke a binary on the system and therefore accept the same flags from all shells.\n \n However, some commands are instead built into the shell and therefore accept different flags depending on which shell is running them.\n \n You have specified `sh` or `dash` in the shebang, but the flags you are using only works when it's executed in e.g. `bash`. You should either explicitly declare that the script requires `bash` to run, or you should only use features that work on all shells. \n \n ### Exceptions:\n \n If the code is gated on a check of the current shell, you can [[ignore]] this warning.\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: In POSIX sh, `source` in place of `.` is undefined. [SC3046]"},{"from": "gpt", "value": "## In POSIX sh, `source` in place of `.` is undefined.\n \n (or \"In dash, ... is not supported.\" when using `dash`)\n \n ### Problematic code:\n \n ```sh\n #!/bin/sh\n source mylib.sh\n ```\n \n ### Correct code:\n \n ```sh\n #!/bin/sh\n . mylib.sh\n ```\n \n ### Rationale:\n \n `source` is a bash and ksh specific alias for the harder-to-pronounce/search command `.` (\"dot\")\n \n When writing for `dash` or `sh`, use `.` instead.\n \n ### Exceptions:\n \n If you only intend to target shells that supports this feature, you can change\n the shebang to a shell that guarantees support, or [[ignore]] this warning.\n \n You can use `# shellcheck disable=SC3000-SC4000` to ignore all such compatibility\n warnings.\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: In POSIX sh, trapping ERR is undefined. [SC3047]"},{"from": "gpt", "value": "## In POSIX sh, trapping ERR is undefined.\n \n (or \"In dash, ... is not supported.\" when using `dash`)\n \n Also applies to RETURN and DEBUG.\n \n ### Problematic code:\n \n ```sh\n #!/bin/sh\n trap 'Command failed with $?' ERR\n ```\n \n ### Correct code:\n \n Switch to a shell like `ksh` or `bash` that *does* support the kind of trap you want:\n \n ```sh\n #!/bin/bash\n trap 'Command failed with $?' ERR\n ```\n \n Otherwise, rewrite the script to not rely on the trap.\n \n ### Rationale:\n \n You are trying to install a trap that is not supported by your current shell (`dash` or POSIX `sh`). There is no simple replacement. The script should be rewritten to avoid depending on the trap, or simply be run with a shell that supports it.\n \n ### Exceptions:\n \n If you only intend to target shells that supports this feature, you can change\n the shebang to a shell that guarantees support, or [[ignore]] this warning.\n \n You can use `# shellcheck disable=SC3000-SC4000` to ignore all such compatibility\n warnings.\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: In POSIX sh, prefixing signal names with 'SIG' is undefined. [SC3048]"},{"from": "gpt", "value": "## In POSIX sh, prefixing signal names with 'SIG' is undefined.\n \n (or \"In dash, ... is not supported.\" when using `dash`)\n \n ### Problematic code:\n \n ```sh\n trap 'handle_interrupt' SIGINT\n ```\n \n ### Correct code:\n \n ```sh\n trap 'handle_interrupt' INT\n ```\n \n ### Rationale:\n \n POSIX does not allow specifying the \"SIG\" prefix of a signal name like \"INT\". Bash and Ksh supports this as an extension.\n \n Simply remove the \"SIG\" from the signal name. \n \n ### Exceptions:\n \n None\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: In POSIX sh, using lower/mixed case for signal names is undefined. [SC3049]"},{"from": "gpt", "value": "## In POSIX sh, using lower/mixed case for signal names is undefined.\n \n ### Problematic code:\n \n ```sh\n trap 'handle_sigint' int\n ```\n \n ### Correct code:\n \n ```sh\n trap 'handle_sigint' INT\n ```\n \n ### Rationale:\n \n POSIX requires that signal names [be given in uppercase](https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_28):\n \n >The condition can be EXIT, 0 (equivalent to EXIT), or a signal specified using a symbolic name, without the SIG prefix, as listed in the tables of signal names in the header defined in XBD Headers; for example, HUP, INT, QUIT, TERM. Implementations may permit names with the SIG prefix or ignore case in signal names as an extension. \n \n ### Exceptions:\n \n None\n \n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: In POSIX sh, `printf %q` is undefined. [SC3050]"},{"from": "gpt", "value": "## In POSIX sh, `printf %q` is undefined.\n \n (or \"In dash, ... is not supported.\" when using `dash`)\n \n ### Problematic code:\n \n ```sh\n ssh host \"cat $(printf \"%q\" \"$remotefile\")\"\n ```\n \n ### Correct code:\n \n There is not really a good, built-in way to escape a string for a remote shell in POSIX sh. However, you can replace each `'` in the input with `'\\''` and then wrap the whole results in single quotes:\n \n ```sh\n escape() { printf \"'%s'\\\\n\" \"$(printf '%s' \"$1\" | sed -e \"s/'/'\\\\\\\\''/g\")\"; }\n ssh host \"cat $(escape \"$remotefile\")\"\n ```\n \n Alternatively, switch to a shell that *does* support `printf %q` like `ksh` or `bash`.\n \n ### Rationale:\n \n `printf %q` is a bash and ksh extension. It's not supported on POSIX sh or dash.\n \n ### Exceptions:\n \n If the command is gated by a check for the correct shell, you can [[ignore]] this warning.\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: In POSIX sh, `source` in place of `.` is undefined [SC3051]"},{"from": "gpt", "value": "## In POSIX sh, `source` in place of `.` is undefined\n \n \n ### Problematic code:\n \n ```sh\n #!/bin/sh\n source /usr/lib/myfile.sh\n ```\n \n ### Correct code:\n \n ```sh\n #!/bin/sh\n . /usr/lib/myfile.sh\n ```\n \n ### Rationale:\n \n Your script uses a shell feature not supported by the shebang. Either rewrite the script to be portable, or change the shebang to explicitly require a shell like Bash.\n \n `source` is a Bash/Ksh specific, readable synonym for `.`. In this case, you can for the most part easily replace `source` with `.`\n \n Do note that `source myfile` in POSIX sh only searches `$PATH`, while Bash/Ksh will additionally search the current directory.\n \n ### Exceptions:\n \n None\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: In POSIX sh, arithmetic base conversion is undefined [SC3052]"},{"from": "gpt", "value": "## In POSIX sh, arithmetic base conversion is undefined\n \n \n ### Problematic code:\n \n ```sh\n #!/bin/sh\n echo \"Hex $1 is decimal $((16#$1))\"\n ```\n \n ### Correct code:\n \n ```sh\n #!/bin/sh\n echo \"Hex $1 is decimal $(echo \"ibase=16; $1\" | bc)\"\n ```\n \n ### Rationale:\n \n Your script uses a shell feature not supported by the shebang. Either rewrite the script to be portable, or change the shebang to explicitly require a shell like Bash.\n \n In this case, using radix specifiers in arithmetic contexts, such as `$((16#DEADBEEF))` is not portable. `bc` ibase/obase can be used instead.\n \n ### Exceptions:\n \n None\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: In POSIX sh, indirect expansion is undefined. [SC3053]"},{"from": "gpt", "value": "## In POSIX sh, indirect expansion is undefined.\n \n (or \"In dash, ... is not supported.\" when using `dash`)\n \n ### Problematic code:\n \n ```sh\n #!/bin/sh\n name=\"PATH\"\n echo \"${!name}\"\n ```\n \n ### Correct code:\n \n The easiest solution is to switch to a shell that does support indirect expansion, like `bash`:\n \n ```sh\n #!/bin/bash\n name=\"PATH\"\n echo \"${!name}\"\n ```\n \n Alternatively, carefully rewrite using `eval`:\n \n ```sh\n #!/bin/sh\n name=PATH\n eval \"echo \\\"\\$$name\\\"\"\n ```\n \n ### Rationale:\n \n Indirection expansion is an extension in `bash` and `ksh`, and not supported in `dash` or POSIX `sh`. Either switch to a shell that supports them, or write around it with careful use of `eval`. Take care to validate the variable name to avoid fragility and code injection.\n \n ### Exceptions:\n \n If you only intend to target shells that supports this feature, you can change\n the shebang to a shell that guarantees support, or [[ignore]] this warning.\n \n You can use `# shellcheck disable=SC3000-SC4000` to ignore all such compatibility\n warnings.\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: In POSIX sh, array references are undefined. [SC3054]"},{"from": "gpt", "value": "## In POSIX sh, array references are undefined.\n \n (or \"In dash, ... are not supported.\" when using `dash`)\n \n ### Problematic code:\n \n ```sh\n #!/bin/sh\n var=(foo bar)\n echo \"${var[1]}\"\n ```\n \n ### Correct code:\n \n The easiest solution is to switch to a shell that does support arrays, like `bash`:\n \n ```sh\n #!/bin/bash\n var=(foo bar)\n echo \"${var[1]}\"\n ```\n \n Alternatively, rewrite the logic to use e.g. indirect variable references or `set`:\n \n ```sh\n #!/bin/sh\n set -- foo bar\n echo \"$2\"\n ```\n \n ### Rationale:\n \n Arrays are supported in `bash` and `ksh`, but not in `dash` or POSIX `sh`. Either switch to a shell that supports them, or rewrite your script without relying on arrays. This may not be straight forward.\n \n ### Exceptions:\n \n If you only intend to target shells that supports this feature, you can change\n the shebang to a shell that guarantees support, or [[ignore]] this warning.\n \n You can use `# shellcheck disable=SC3000-SC4000` to ignore all such compatibility\n warnings.\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: In POSIX sh, array key expansion is undefined. [SC3055]"},{"from": "gpt", "value": "## In POSIX sh, array key expansion is undefined.\n See similar array warning [[SC3054]].\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: In POSIX sh, name matching prefixes are undefined. [SC3056]"},{"from": "gpt", "value": "## In POSIX sh, name matching prefixes are undefined.\n \n (or \"In dash, ... are not supported.\" when using `dash`)\n \n ### Problematic code:\n \n ```sh\n #!/bin/sh\n echo \"${!ANDROID_*}\"\n ```\n \n ### Correct code:\n \n The easiest solution is to switch to a shell that *does* support name matching prefixes, like `bash`:\n \n ```sh\n #!/bin/bash\n echo \"${!ANDROID_*}\"\n ```\n \n Alternatively, extract the data you want from `env` or `set`\n \n ### Rationale:\n \n Using `${!name*}` to find all variable names with a given prefix is a bash and ksh extension that `dash` and POSIX `sh` does not support.\n \n ### Exceptions:\n \n If you only intend to target shells that supports this feature, you can change\n the shebang to a shell that guarantees support, or [[ignore]] this warning.\n \n You can use `# shellcheck disable=SC3000-SC4000` to ignore all such compatibility\n warnings.\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: In POSIX sh, string indexing is undefined. [SC3057]"},{"from": "gpt", "value": "## In POSIX sh, string indexing is undefined.\n \n (or \"In dash, ... is not supported.\" when using `dash`)\n \n ### Problematic code:\n \n ```sh\n #!/bin/sh\n echo \"Your initial is ${USER:0:1}\"\n ```\n \n ### Correct code:\n \n Either switch to a shell that does support string indexing via parameter expansion, like `bash` or `ksh`, or rewrite with `cut`:\n \n ```sh\n #!/bin/sh\n echo \"Your initial is $(printf '%s' \"$USER\" | cut -c 1)\"\n ```\n \n To find the last argument passed to a shell script without using bash’s `${@:$#}`- or `${@: -1}`-style string indexing, use the following, which even “[works in the unix v7 bourne shell from 1979](https://stackoverflow.com/q/1853946#comment104235724_1853993)”:\n \n ```sh\n #!/bin/sh\n for argument in \"$@\"; do\n : # `:`, also called as `true`, is a no-op here\n done\n printf '%s\\n' \"${argument-}\"\n ```\n \n ### Rationale:\n \n String indexing is a bash and ksh extension, and does not work in `dash` or POSIX `sh`.\n \n ### Exceptions:\n \n If you only intend to target shells that supports this feature, you can change\n the shebang to a shell that guarantees support, or [[ignore]] this warning.\n \n You can use `# shellcheck disable=SC3000-SC4000` to ignore all such compatibility\n warnings.\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: Case modification is not supported in dash and undefined in POSIX sh. [SC3059]"},{"from": "gpt", "value": "Case modification is not supported in dash and undefined in POSIX sh.\n \n https://github.com/sbaudoin/sonar-shellcheck/blob/master/src/main/scripts/build_checks.yml\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: In POSIX sh, string replacement is undefined. [SC3060]"},{"from": "gpt", "value": "## In POSIX sh, string replacement is undefined.\n \n (or \"In dash, ... is not supported.\" when using `dash`)\n \n ### Problematic code:\n \n ```sh\n #!/bin/sh\n echo \"${var//foo/bar}\"\n ```\n \n ### Correct code:\n \n Either switch the shebang to `bash` or `ksh`, or rewrite the expansion using a tool like `sed`:\n \n ```sh\n #!/bin/sh\n echo \"$var\" | sed 's/foo/bar/g'\n ```\n \n ### Rationale:\n \n String replacement in parameter expansion is a `bash` and `ksh` extension. `dash` and POSIX `sh` does not support it.\n \n ### Exceptions:\n \n If you only intend to target shells that supports this feature, you can change\n the shebang to a shell that guarantees support, or [[ignore]] this warning.\n \n You can use `# shellcheck disable=SC3000-SC4000` to ignore all such compatibility\n warnings.\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ], [ {"from": "human", "value": "Tell me about this shellcheck error in my shell script: In POSIX sh, unary -o to check options is undefined. [SC3062]"},{"from": "gpt", "value": "## In POSIX sh, unary -o to check options is undefined.\n \n ### Problematic code:\n \n ```sh\n if [ -o braceexpand ]\n then\n echo \"Brace expansion available and enabled.\"\n fi\n ```\n \n ### Correct code:\n \n `$-` will be set to a list of shell options:\n \n ```sh\n case $- of\n *B*) echo \"Brace expansion available and enabled.\"\n esac \n ```\n \n However, not all options are available through `$-`. If you need to check those, ignore this suggestion with a directive:\n \n ```sh\n # shellcheck disable=SC3062\n if [ -n \"$BASH_VERSION\" ] && [ -o pipefail ]\n then\n echo \"This is bash and pipefail is enabled.\"\n fi\n ```\n \n ### Rationale:\n \n `[ -o option ]` is a bash/ksh extension, while `$-` is standard POSIX. Do note that letters outside the POSIX set are not guaranteed to be compatible, such as `B` above.\n \n ### Exceptions:\n \n As described.\n \n ### Related resources:\n \n * Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!\n"} ] ]}