我还没有找到任何可以解决这种特殊情况的事情。也许有一种简单的方法,我可以忽略而不是检查一个字符串来捕捉这种情况。当我检查输入是否存在文件时,如果输入为~/filecheck
,则不会起作用。当文件在我的主文件夹中时,我得到负面结果。任何改进脚本任何部分的建议我一定会很感激。我还必须使用输入而不是参数。谢谢你的帮助。
我的测试脚本
read -p "Enter: " input
echo $input
if [ -f $input ]; then
read -p "Do you REALLY want to delete this file?:" input2
if [[ $input2='y' || $input2 = 'Y' ]]
then
rm -f $input
elif [[ $input2='n' || $input2='N' ]]
then
exit
else
echo "Invaild Option"
exit
fi
else
echo Invaild Option!
exit
fi
答案 0 :(得分:2)
如果不使用基于eval
的内容,则无法在程序的这一部分进行代码扩展 - 并且您不希望通过用户输入执行此操作。因此,您的穷人解决方案将用~/
的扩展替换任何潜在的前导$HOME/
。这里以适当的更好的风格改编你的剧本:
#!/bin/bash
read -e -p "Enter: " input
input=${input/#~\//$HOME/} # <--- this is the main idea of this answer (and it's rather poor)
echo "$input"
if [[ -f $input ]]; then
read -e -p "Do you REALLY want to delete this file? " input2
if [[ ${input2,,} = y ]]; then
rm -f -- "$input"
elif [[ ${input2,,} = n ]]; then
exit
else
echo "Invalid Option"
exit
fi
else
echo "Invalid Option!"
fi
exit
现在,出于好奇,你为什么要花时间围绕rm
做一个包装?你正在为一个已经存在的程序制作一个笨重的界面,而不向它添加任何内容,只会使它不那么强大且不易使用。
答案 1 :(得分:1)
由于您输入的输入字符串为~/filecheck
,因此在-f
[ -f $input ]
条件时,shell不会展开波浪号
您可以这样使用,但不推荐使用它,因为用户可以运行任意命令,因此可能存在危险:
if [[ -f $(bash -c "echo $input") ]]; then
echo "file exists"
fi
编辑:根据以下评论,以避免冒险bash -c
,您可以使用:
if [[ -f "${input/\~/$HOME}" ]]; then
echo "file exists"
fi
答案 2 :(得分:0)
如果你想要的所有内容在删除之前询问用户,你可以使用:
rm -i
如果文件不存在,这将为您提供适当的错误。