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

时间:2012-01-23 11:38:36

标签: linux bash

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

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

有人能看出什么问题吗?

#!/bin/sh

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

4 个答案:

答案 0 :(得分:48)

尝试添加额外的方括号。

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

答案 1 :(得分:30)

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

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

另外,如果您使用[[ ]]解决方案,则可能需要根据问题的标记将#!/bin/sh更改为#!/bin/bash

答案 2 :(得分:12)

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

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

答案 3 :(得分:7)

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

下面,

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

-f也做同样的事情但是,检查给定的文件是否是普通文件。基于它返回true / false。

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

相反,你可以使用-a [和&& operator] -o [与||相同运营商。 如果您需要更多信息,请通过此链接

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