假设我有一个 shell 脚本 test.sh
,它应该回显一些值。我希望能够通过具有 glob 扩展的环境变量传递这些值:
$ ls
1.js 2.js test.sh*
$ FOO="*.js" bash ./test.sh
1.js 2.js
简单,你说!随便写
#!/bin/bash
echo $FOO
确实,这行得通。但它没有通过 ShellCheck ,这要求我们使用隐式通配/扩展( SC2086 )。 (这是公平的;在原始代码中,回显行是 cp $FOO $BAR
,我们确实不想在此处展开 $BAR
;此错误会捕获错误。)
因此,为了使这一点更加明确,我希望以下内容可能会起作用:
#!/bin/bash
array=( $FOO )
echo "${array[@]}"
但不是:我们最终得到 SC2206 .
是否有一种规范的方式来做这种事情,这属于 ShellCheck 作者认为的最佳实践? (请随意使用 www.shellcheck.net 上的在线检查器对其进行测试。)这是完全错误的方法吗? ShellCheck 作者似乎不太可能从未想过这个用例......
最佳答案
在这种情况下,似乎没有针对 ShellCheck 警告的安全解决方法。然而,ShellCheck 的诊断并不是普遍真理。您可能已经注意到,其某些警告的文档包括一个异常(exception)部分。对于 SC2206上面写着:
Exceptions:
If you have already taken care (through setting
IFS
andset -f
) to have word splitting work the way you intend, you can ignore this warning.
现在,ShellCheck 提供directives根据具体情况忽略警告:
Shellcheck directives allow you to selectively ignore warnings, and takes the form of comments in files:
hexToAscii() { # shellcheck disable=SC2059 printf "\x$1" }
Supported directives are
disable
to disable warnings:# shellcheck disable=code[,code...] statement_where_warning_should_be_disabled
...
Directives instead of or immediately after the shebang apply to the entire script. Otherwise, they are scoped to the structure that follows it (such as all branches of a case statement, or an entire function).
因此您可以按如下方式抑制您的警告:
#!/usr/bin/env bash
# The following line is needed so that the shellcheck directive
# below doesn't have global effect
:
# shellcheck disable=SC2206
array=( $FOO )
echo "${array[@]}"
关于bash - 如何在传递 ShellCheck 时通过环境变量将 glob 传递给 shell 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45931553/