Linux 如何测试两个文件是否存在?

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

How to test for if two files exist?

linuxbash

提问by Sandra Schlichting

I would like to check if both files exist, but I am getting

我想检查两个文件是否存在,但我得到

test.sh: line 3: [: missing `]'

Can anyone see what's wrong?

任何人都可以看到有什么问题吗?

#!/bin/sh

if [ -f .ssh/id_rsa && -f .ssh/id_rsa.pub ]; then
   echo "both exist"
else
   echo "one or more is missing"
fi

采纳答案by Raghuram

Try adding an additional square bracket.

尝试添加一个额外的方括号。

if [[ -f .ssh/id_rsa && -f .ssh/id_rsa.pub ]]; then

回答by Michael Krelin - hacker

[ -f .ssh/id_rsa -a -f .ssh/id_rsa.pub ] && echo both || echo not

or

或者

[[ -f .ssh/id_rsa && -f .ssh/id_rsa.pub ]] && echo both || echo not

also, if you for the [[ ]]solution, you'll probably want to change #!/bin/shto #!/bin/bashin compliance with your question's tag.

此外,如果您[[ ]]想要解决方案,您可能希望更改#!/bin/sh#!/bin/bash符合您问题的标签。

回答by j?rgensen

[[is bash-specific syntax. For POSIX-compatible shells, you need:

[[是 bash 特定的语法。对于 POSIX 兼容的 shell,您需要:

[ -f file1 ] && [ -f file2 ]

回答by sat

if [ -e .ssh/id_rsa -a -e .ssh/id_rsa.pub ]; then
 echo "both exist"
else
 echo "one or more is missing"
fi

Here,

这里,

-e check only the file is exits or not.If exits,it return true.else,it return false.

-e 只检查文件是否退出。如果退出,则返回true。否则返回false。

-f also do the same thing but,it check whether the given file is regular file or not.based on that it return the true/false.

-f 也做同样的事情,但是,它检查给定的文件是否是常规文件。基于它返回真/假。

Then you are using &&.So that,It need two [[ .. ]] brackets to execute.

然后你使用&&。所以,它需要两个 [[ .. ]] 括号来执行。

instead you can use the -a [same as && operator] -o [same as || operator]. If you need more information go through this link

相反,您可以使用 -a [与 && 运算符相同] -o [与 || 相同 操作员]。如果您需要更多信息,请访问此链接

http://linux.die.net/man/1/bash.

http://linux.die.net/man/1/bash