gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 09:50:37 43 4
gpt4 key购买 nike

我在下面代码的第二行收到 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/

43 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com