Unable to delete a file using bash script
- by user3719091
I'm having problems removing a file in a bash script. I saw the other post with the same problem but none of those solutions solved my problem. The bash script is an OP5 surveillance check and it calls an Expect process that saves a temporary file to the local drive which the bash script reads from. Once it has read the file and checked its status I would like to remove the temporary file. I'm pretty new to scripting so my script may not be as optimal as it can be. Either way it does the job except removing the file once it's done. I will post the entire code below:
#!/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
I have tried the following solutions:
Create a separate variable called TempFile that specifies the file. And specify that in the rm command.
I tried creating another if statement similar to the one I use to verify that file exist and then rm the filename.
I tried adding the complete name of the file (no variables, just plain text of the file)
I can:
Remove the file using the full name in both a separate script and directly in the CLI.
Is there something in my script that locks the file that prevents me from removing it? I'm not sure what to try next.
Thanks in advance!