1) Use "read input" not "read $input".
2) Test for the file (-f) not the environment variable (-z)
3) Echo your "rm" statement while testing to be sure what will be deleted
4) Don't use "rm -rf" - it deletes the directory too!
5) Test with "rm -i" (interactive) to give you chance of not deleting something unintentional
#!/bin/bash
echo "Enter file to delete from tmp"
read input
filename="/tmp/${input}"
if [ ! -f "${filename}" ]
then
echo "File Doesnt Exist"
else
echo rm -i "${filename}"
fi
What if i need to schedule the script at midnight I can't use any interactive option .How would i avoid this risk for automated script without any manual intervention.
---------- Post updated at 06:43 AM ---------- Previous update was at 06:35 AM ----------
I have modified the code . Please share your views on the modified script.
#!/bin/bash
echo "Enter file or folder to delete from tmp"
read input
if [ ! -f "/tmp/$input" ]
then
echo "File Doesnt Exist"
else
rm -r "/tmp/$input"
fi