linux - bash 脚本 while 循环读取来自用户的输入

标签 linux bash shell

<分区>

想知道是否有一种简单的方法来完成我正在尝试的事情以及进行此类操作的最佳方法。

answer=y 
while [ "$answer" = y ]
do 
    echo "type name of the file you wish to delete"
    IFS= read -r file
    echo "would you like to delete another file [y/n]?"
    IFS= read -r answer
done 

echo "Exiting Program"
exit 0 

我的问题是,当输入输入时,它会存储在文件中,但我希望当答案为 y 时,它可以存储到另一个变量,如 file1。 然后我留下了包含有人希望删除的所有文件名的变量,我可以回显这些文件名。

我如何在其中使用循环来不断添加输入,直到有人键入 n

感谢您的帮助。

最佳答案

我不会使用实时读取循环来删除文件。太多的事情可能会出错。相反,也许获取一个输入文件并检查每个文件。

但是对于您的问题的简单回答-

typeset -l answer=y  # force to lowercase
lst=/tmp/file.list.$$
while [[ y == "$answer" ]]
do 
    echo "type name of the file you wish to delete"
    IFS= read -r file
    if [[ -e "$file" ]]
    then echo "$file" >> $lst
    else echo "That file does not exist/is not accessible."
    fi
    echo "would you like to delete another file [y/n]?"
    IFS= read -r answer
done 
echo -e "Files to be deleted:\n===\n$(<$lst)"
echo -e "\n===\n Delete all listed files [y/n]?"
IFS= read -r answer
if [[ y == "$answer" ]]
then rm $(<$lst)
fi
rm $lst

关于linux - bash 脚本 while 循环读取来自用户的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46607012/

相关文章:

linux - Amazon Linux AMI EC2 - 缺少包

bash - 比较两个文件中的值

java - 无法使用 .sh 文件运行我的 .jar 文件

linux - 当使用 ffmpeg 将脚本传输到 bash 时,第一个字符消失

c++ - 执行 Shell 命令时的性能问题

linux - 递归查找 ".sh"文件,然后在该路径上执行我的 .sh 文件

linux - 读取NAND闪存并将其写入另一个系统

bash - 在 less 命令中查找以前的搜索

linux - 在不使用循环的情况下使用 bash 在终端中显示运行时钟

regex - 使用 sed 更改文件扩展名