我想检查是否存在这两个文件,但我正在逐渐如何测试两个文件是否存在?
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
。
[[
是bash特有的语法。对于POSIX兼容的炮弹,你需要:
[ -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只检查文件是退出或not.If退出,其返回true.else,它返回false。
-f也做同样的事情,但它检查给定的文件是否是普通文件或不是。基于它返回true/false。
然后你正在使用& &。所以,它需要两个[[..]]括号来执行。
改为您可以使用-a [与& &运算符相同] -o [与||相同]运营商。 如果您需要更多信息,请通过此链接
如果您使用'测试'而不是'[',问题更加明显。 “如果测试-f .ssh/id_rsa && test -f .ssh/ir_rsa.pub;那么”工作得很好。 –