Unix找到一个文件,然后提示删除

时间:2013-09-10 19:04:02

标签: shell unix

我目前正在学习Unix,并在一本书中遇到了一个问题,我正试图解决这个问题。

我正在尝试编写一个要求用户输入文件名的脚本。 然后,脚本需要检查文件是否存在。如果该文件不存在,该脚本应显示错误消息,然后退出该脚本。 如果文件存在,脚本应询问用户是否确实要删除该文件。 如果答案为是或y,则脚本应删除该文件。 如果答案为no或n,则脚本应退出脚本。 如果答案既不是也不是,则脚本应显示错误消息并退出脚本。

这是我到目前为止所写的,但却遇到了一些错误:

#!/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

如果有人来解释我哪里出错了,我们将不胜感激

2 个答案:

答案 0 :(得分:1)

我建议使用这种形式:

#!/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

此外,您可以在提示中添加-n选项,只接受一个密钥,不再需要输入密钥:

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

我顺便错误地在echo之前添加了read。它现在已经修好了。

    echo read ...

答案 1 :(得分:0)

以最简单的形式,您可以执行以下操作:

$ rm -vi file

举个例子:

$ 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'