【问题标题】:Unix find a file and then prompting to delete [duplicate]Unix找到一个文件然后提示删除[重复]
【发布时间】:2013-09-14 15:13:33
【问题描述】:

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

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

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

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

【问题讨论】:

  • 我将其标记为重复,因为我认为这是关于如何在 bash 中实现是/否问题的问题。我在下面给出的答案是如何使用命令rm 实现相同的结果

标签: bash shell unix


【解决方案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

您在read 之前添加了echo,我将其删除。

【讨论】:

  • necroposting,但是在这里加双引号不是更安全吗:[[ -f "$file" ]],如果不是,为什么?
  • @DaemonPainter 这没什么区别,因为[[ ]] 是bash 中的关键字(问题有#!/bin/bash)。参数不会在其中进行单词拆分或文件名/路径名扩展(也称为通配符)。仅当参数是模式并且您想逐字比较变量中的字符串时才重要。例如。 [[ $string == *"${partial}"* ]].
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 2014-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-10
    • 1970-01-01
    • 1970-01-01
    • 2020-09-25
    • 2021-06-09
    相关资源
    最近更新 更多