0

I'm currently learning Unix and have come across a question in a book that I'm trying to solve.

I'm trying to write a script that asks a user to enter a file name. Then, the script needs to check for file existence. If the file does not exist, that script should display an error message and then exit the script. If the file exists, the script should ask if the user wants to delete the file:

  • If the answer is yes or y, the script should remove the file.
  • If the answer is no or n, the script should exit from the script.
  • If the answer is neither yes nor no, the script should display an error message and exit from the script.

This what I have written so far but have come across with a few errors:

#!/bin/bash

file=$1

if [ -f $file ];
then
echo read -p  "File $file existes,do you want to delete y/n" delete
case $delete in
n)
   exit
y) rm $file echo "file deleted";;
else
echo "fie $file does not exist"
exit
fi

If anyone come explain where I have gone wrong it would be greatly appreciated

kvantour
  • 25,269
  • 4
  • 47
  • 72
user2141414
  • 101
  • 1
  • 3
  • 10
  • I mark this as a duplicate as I believe this is question is about how to implement a yes/no question in bash. The answer I present below is how you can achieve the same result with the command `rm` – kvantour Oct 02 '19 at 19:19

2 Answers2

2

I'd suggest this form:

#!/bin/bash

file=$1

if [[ -f $file ]]; then
    read -p "File $file exists. Do you want to delete? [y/n] " delete
    if [[ $delete == [yY] ]]; then  ## Only delete the file if y or Y is pressed. Any other key would cancel it. It's safer this way.
        rm "$file" && echo "File deleted."  ## Only echo "File deleted." if it was actually deleted and no error has happened. rm probably would send its own error info if it fails.
    fi
else
    echo "File $file does not exist."
fi

Also you can add -n option to your prompt to just accept one key and no longer require the enter key:

    read -n1 -p "File $file exists. Do you want to delete? [y/n] " delete

You added echo before read and I removed it.

konsolebox
  • 72,135
  • 12
  • 99
  • 105
  • necroposting, but wouldn't it be safer to put double quotes here: `[[ -f "$file" ]]`, if no, why? – Daemon Painter Oct 02 '19 at 09:15
  • 1
    @DaemonPainter It doesn't make a difference because `[[ ]]` is a keyword in bash (question has `#!/bin/bash`). Arguments don't do word split or filename/pathname expansion (a.k.a. globbing) in it. It only matters if the argument is a pattern and you want to compare the string in the variable literally. E.g. `[[ $string == *"${partial}"* ]]`. – konsolebox Oct 02 '19 at 19:15
0

In it's simplest form, you could do the following:

$ rm -vi file

To give you an example:

$ mkdir testdir; touch testdir/foo; cd testdir; ls
foo
$ rm -vi bar
rm: cannot remove 'bar': No such file or directory
$ rm -vi foo
rm: remove regular empty file 'foo'? y
removed 'foo'
kvantour
  • 25,269
  • 4
  • 47
  • 72