bash - ShellCheck 警告 : "Iterating over ls output is fragile. Use globs. [SC2045]"

标签 bash ls shellcheck

我在下面代码的第二行收到 ShellCheck 警告 [SC2045]。可以忽略它吗,因为我在尝试最后一个 ls 之前要确保目录不为空?

 if [ "$(ls -A "$retryDir")" ]  ; then
    for thisRetryFile in $(ls "$retryDir"/*.tar.gz) ; do
        scp -o ConnectTimeout=30  "$thisRetryFile"  \             
              "$remoteUser@$remoteHost:$remotePath" >> "$BACKUPLOG"
    done
 fi

更新: 看完帖子评论。我已将行更改为:

for thisRetryFile in "$retryDir"/*.tar.gz ; do

这已删除警告。

最佳答案

使用带有 glob 的循环,并设置 nullglob 以避免在模式不匹配任何内容的情况下执行 scp。 而且您也不需要外部 if 条件, 因为带有 nullglobfor 有效地处理了这一点:

shopt -s nullglob

for thisRetryFile in "$retryDir"/*.tar.gz; do
    scp -o ConnectTimeout=30  "$thisRetryFile" \
          "$remoteUser@$remoteHost:$remotePath" >> "$BACKUPLOG"
done

如果你想在没有文件匹配模式时捕捉到这种情况, 你可以这样写,不用 shopt -s nullglob:

for thisRetryFile in "$retryDir"/*.tar.gz; do
    if [ -f "$thisRetryFile" ]; then
        scp -o ConnectTimeout=30  "$thisRetryFile" \
            "$remoteUser@$remoteHost:$remotePath" >> "$BACKUPLOG"
        break
    else
        echo "warn: no tar.gz file in dir: $retryDir"
    fi
done

关于bash - ShellCheck 警告 : "Iterating over ls output is fragile. Use globs. [SC2045]",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47702490/

相关文章:

Linux 列表文件递归地忽略模式

bash - 是否可以在使用位置变量时解析 SC2001 ("See if you can use ${variable//search/replace} instead")?

shell - 使用 ShellCheck 进行 shell 脚本的静态代码分析 - 预定义规则

bash - 如何用find和sed生成随机数?

linux - Bash 脚本警告 - HERE 文档由文件末尾分隔

Bash,检查命令返回然后回显它

c - 在 X 时间运行 Bash 命令并终止 X 时间

shell - 使用 ls 列出所有与模式不匹配的文件

unix - 如何通过排除某些文件扩展名来搜索 unix 中的一个或多个目录

bash - 这个错误是什么意思? (SC2129 : Consider using { cmd1; cmd2; } >> file instead of individual redirects.)