我还没有找到任何方法来处理这种特殊情况。也许我忽略了一种简单的方法,而不是检查字符串来捕获这种情况。当我检查输入是否存在文件时,如果输入是 ~/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
最佳答案
由于您输入的字符串为 ~/filecheck
shell 在 [ -f $input ]< 中使用
-f
条件时不会扩展波浪号
您可以这样使用它但不推荐这样做并且有潜在危险,因为用户可以运行任意命令:
if [[ -f $(bash -c "echo $input") ]]; then
echo "file exists"
fi
编辑:根据下面的评论,为了避免有风险的 bash -c
,您可以使用:
if [[ -f "${input/\~/$HOME}" ]]; then
echo "file exists"
fi
关于Bash + 检查文件是否存在,路径为 home ~,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24344037/