我在下面代码的第二行收到 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
条件,
因为带有 nullglob
的 for
有效地处理了这一点:
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/