0

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

我正在尝试编写一个要求用户输入文件名的脚本。然后,脚本需要检查文件是否存在。如果该文件不存在,该脚本应显示一条错误消息,然后退出该脚本。如果文件存在,脚本应该询问用户是否要删除文件:

  • 如果答案为是或是,则脚本应删除该文件。
  • 如果答案为否或 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

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

4

2 回答 2

2

我建议这种形式:

#!/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的,我删了。

于 2013-09-10T19:11:35.557 回答
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'
于 2019-10-02T19:15:03.040 回答