little confusion about variable initialization.

Whenever i execute the below scriptlet with out proper file name it deletes /tmp directory .

I guess this is because value of variable a didnt get initialized and there for rm -rf /tmp/ get executed and entire /tmp directory get deleted.

How would i avoid any empty variables to be used in script? as this is a classic case of destructive script.

#!/bin/bash

echo "Enter file to delete from tmp"
read input
a=`ls /tmp/$input`
if [ -z "/tmp/$a" ]
then
echo "File Doesnt Exist"
else
rm -rf /tmp/$a
fi

Hi.

Test that it's set. i.e.

unset input
while [[ -z $input ]]; do
  read input
done  

Maybe a case statement is better:

unset input
while [[ -z $input ]]; do
  read input
  case "$input" in
   .|..|"") unset input;;
   esac
done 

Instead read $input try read input.

Good spot :slight_smile:

#!/bin/bash

echo "Enter file to delete from tmp"
read a
  if [ ! -e "/tmp/$a" ]
     then
     echo "File Doesnt Exist"
      else
        rm -f /tmp/$a
  fi

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
1 Like

Thanks methyl for making all points clear, Really appreciate.

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

Don't use "-r" for files, use "-f".

rm -f "/tmp/$input"

As for scheduling the job, where does the list of file names come from? (It can't come from someone typing at a keyboard).

methyl has suggested me to use rm -i which is interactive i was replying to his suggestion.
Anyway thanks for ur reply.