如何检查文件是否存在于 bash 脚本的特定目录中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29927005/
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-09-18 12:53:30  来源:igfitidea点击:

How to check if a files exists in a specific directory in a bash script?

linuxbashfilescriptingterminal

提问by Bob

This is what I have been trying and it is unsuccessful. If I wanted to check if a file exists in the ~/.example directory

这是我一直在尝试的,但没有成功。如果我想检查 ~/.example 目录中是否存在文件

FILE=
if [ -e $FILE ~/.example ]; then
      echo "File exists"
else
      echo "File does not exist"
fi

回答by Eric Renouf

You can use $FILEto concatenate with the directory to make the full path as below.

您可以使用$FILE与目录连接以制作如下完整路径。

FILE=""
if [ -e ~/.myexample/"$FILE" ]; then
    echo "File exists"
else
    echo "File does not exist"
fi

回答by Jahid

This should do:

这应该做:

FILE=
if [[ -e ~/.example/$FILE && ! -L ~/example/$FILE ]]; then
      echo "File exists and not a symbolic link"
else
      echo "File does not exist"
fi

It will tell you if $FILEexists in the .exampledirectory ignoring symbolic links.

它会告诉您目录中是否$FILE存在.example忽略符号链接。

You can use this one too:

你也可以使用这个:

[[ -e ~/.example/$FILE && ! -L ~/example/$FILE ]] && echo "Exists" || echo "Doesn't Exist"

回答by Alec

Late to the party here but a simple solution is to use -f

迟到了,但一个简单的解决方案是使用 -f

if [[ ! -f $FILE]]
then
  echo "File does not exist"
fi

A few more examples hereif you're curious

如果你好奇,这里还有一些例子