检查文件是否存在 Linux bash

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10663575/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 06:23:34  来源:igfitidea点击:

Check if file exist Linux bash

linuxbashfile

提问by Painguy

So I'm trying to check if a file exists or not and then the script is supposed to do something if it does. The problem I'm having is actually getting it to recognize that something is actually there.

因此,我试图检查文件是否存在,然后脚本应该执行某些操作(如果存在)。我遇到的问题实际上是让它认识到确实存在某些东西。

if [ -e /temp/file.txt ]; then
        echo "file found!"
        sudo cp -r temp/* extra
else
        echo "file not found! Creating new one..."
        ./create.sh
fi

below is an example of the files in the directory I'm testing. they are clearly there, but for some reason I can't get the script to see that. what am I doing wrong?

下面是我正在测试的目录中的文件示例。他们显然在那里,但由于某种原因,我无法让脚本看到这一点。我究竟做错了什么?

nima@mkt:/docs/text$ ls -a temp
.  ..  more  file.txt  file2.txt

采纳答案by Dmitri Chubarov

You are using absolute paths in your test while you should be using relative paths:

您在测试中使用绝对路径,而您应该使用相对路径:

 if [ -e ./temp/file.txt ]; then

回答by John Carter

/temp/file.txtvs /docs/text/temp/file.txt?

/temp/file.txt/docs/text/temp/file.txt?

回答by Sven

You script looks in /tempwhile you are looking in /docs/text/temp

您在查看时脚本/temp会查看/docs/text/temp