我正在为下面代码中的第二行获得一个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这消除了警告。
发布于 2017-12-07 19:50:31
使用带有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发布于 2017-12-07 19:37:29
这更安全。试试看。
if [ "$(ls -A "$retryDir")" ] ; then
for thisRetryFile in ${retryDir}'/*.tar.gz' ; do
scp -o ConnectTimeout=30 "$thisRetryFile" "$remoteUser@$remoteHost:$remotePath" >> "$BACKUPLOG"
done
fi致以问候!
https://stackoverflow.com/questions/47702490
复制相似问题