无法使用 bash 脚本删除文件

无法使用 bash 脚本删除文件

我在删除 bash 脚本中的文件时遇到了问题。我看到了另一篇有同样问题的帖子,但这些解决方案都没有解决我的问题。bash 脚本是一个 OP5 监视检查,它调用一个 Expect 进程,将临时文件保存到 bash 脚本从中读取的本地驱动器。一旦它读取了文件并检查了其状态,我想删除临时文件。我对脚本编写还很陌生,所以我的脚本可能不是最理想的。无论哪种方式,它都能完成工作,只是完成后会删除文件。我将在下面发布整个代码:

#!/bin/bash

#GET FLAGS
while getopts H:c:w: option
do
case "${option}"
in
        H) HOSTADDRESS=${OPTARG};;
        c) CRITICAL=${OPTARG};;
        w) WARNING=${OPTARG};;
esac
done

./expect.vpn.check.sh $HOSTADDRESS

#VARIABLES
VPNCount=$(grep -o '[0-9]\+' $HOSTADDRESS.op5.vpn.results)

# Check if the temporary results file exists
if [ -f $HOSTADDRESS.op5.vpn.results ]
then
# If the file exist, Print "File Found" message
echo Temporary results file exist. Analyze results.

else # If the file does NOT exist, print "File NOT Found" message and send message to OP5
echo Temporary results file does NOT exist. Unable to analyze.
# Exit with status Critical (exit code 2)
exit 2
fi

if [[ "$VPNCount" > $CRITICAL ]]
then
# If the amount of tunnels exceeds the critical threshold, echo out a warning message and current threshold and send warning to OP5
echo "The amount of VPN tunnels exceeds the critical threshold - ($VPNCount)"
# Exit with status Critical (exit code 2)
exit 2

elif [[ "$VPNCount" > $WARNING ]]
then
# If the amount of tunnels exceeds the warning threshold, echo out a warning message and current threshold and send warning to OP5
echo "The amount of VPN tunnels exceeds the warning threshold - ($VPNCount)"
# Exit with status Warning (exit code 1)
exit 1
else
# The amount of tunnels do not exceed the warning threshold.
# Print an OK message
echo OK - $VPNCount
# Exit with status OK
exit 0
fi

#Clean up temporary files.
rm -f $HOSTADDRESS.op5.vpn.results

我尝试过以下解决方案:

  • 创建一个名为 TempFile 的单独变量来指定该文件。并在 rm 命令中指定该文件。

  • 我尝试创建另一个 if 语句,类似于我用来验证文件是否存在然后 rm 文件名的语句。

  • 我尝试添加文件的完整名称(没有变量,只是文件的纯文本)

我可以:

  • 在单独的脚本中和直接在 CLI 中使用全名删除文件。

我的脚本中是否有东西锁定了文件,阻止我删除它?我不确定下一步该尝试什么。

提前致谢!

答案1

当您“退出”时它会退出,并且不会到达脚本的最后一行。

第一个解决方案:将最后一行移到“echo 临时结果文件存在。分析结果。”下面,因为它是文件存在和被分析的地方......

如果您希望在每种情况下都删除该文件,并且每次退出时都不会出现 rm 问题(即,无论退出程序的原因是什么),而不是最后一行,定义(靠近脚本的开头!)一个在程序退出时调用的函数(使用“trap thefonction EXIT”:意思是:当你 EXIT 时调用“thefonction”(或程序收到 ctrl + c))。

function onexit {
   # Your cleanup code here
   rm -f $HOSTADDRESS.op5.vpn.results
}

trap onexit EXIT

但是您需要确保在正确的时间定义陷阱(并且执行此操作时定义了 HOSTADDRESS!)

请注意,如果您“kill -9”该程序,它将根本没有时间使用该陷阱(kill -9 仅在常规 kill 不起作用时使用,因为它不允许程序有任何时间使用清理等...)

相关内容