我想检查两个文件是否都存在,但是我得到了
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
我想检查两个文件是否都存在,但是我得到了
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
if [[ -f .ssh/id_rsa && -f .ssh/id_rsa.pub ]]; then
[[
(无空格)而不是 [ [
(有空格)。不知为何,当我看到这个答案时,我认为有空格也可以,但事实并非如此! - gusterlover6[ -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
,以符合您问题的标签要求。
[[ ]]
也被 ksh
、zsh
和可能其他 shell 支持。但最好使用 #!/bin/bash
而不是 #!/bin/sh
。 - oHo[[
是Bash特定的语法。对于兼容POSIX的Shell,您需要使用:
[ -f file1 ] && [ -f file2 ]
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。否则,返回 false。
-f 也是同样的操作,但它会检查给定的文件是否是普通文件。基于此,它会返回 true/false。
然后您使用 &&。因此,需要两个 [[..]] 括号来执行。
相反,您可以使用 -a [与 && 操作符相同] -o [与 || 操作符相同]。
如果您需要更多信息,请查阅以下链接: