我发现this answer which works很好,但我想明白为什么下面的代码不会检测到两个文件的存在?Bash,测试两个文件的存在
if [[ $(test -e ./file1 && test -e ./file2) ]]; then
echo "yep"
else
echo "nope"
fi
直接从壳作品运行此预期:
test -e ./file1 && test -e ./file2 && echo yes
我发现this answer which works很好,但我想明白为什么下面的代码不会检测到两个文件的存在?Bash,测试两个文件的存在
if [[ $(test -e ./file1 && test -e ./file2) ]]; then
echo "yep"
else
echo "nope"
fi
直接从壳作品运行此预期:
test -e ./file1 && test -e ./file2 && echo yes
的test -e ./file1 && test -e ./file2
输出是一个空字符串,这会导致[[ ]]
以产生非零的退出代码。你想
if [[ -e ./file1 && -e ./file2 ]]; then
echo "yep"
else
echo "nope"
fi
[[ ... ]]
是[ ... ]
或test ...
的替代,而不是围绕它的包装。
if
根据其返回值执行程序(或内置,在[[
的情况下)和分支。您需要忽略无论是[[ ]]
或test
S:
if [[ -e ./file1 && -e ./file2 ]]; then
或者
if test -e ./file1 && test -e ./file2; then
您更新包含shell脚本反模式的一个很好的慷慨洒从http://partmaps.org/era/unix /award.html – tripleee
使用您发现在交互式shell中工作的简单,惯用,正确的代码有什么问题? 'test -e ./file1 && test -e ./file2 && echo yep || echo nope' – tripleee
@tripleee非常感谢您对反模式的链接,我希望那些来这个问题的人会看看[编辑由chepner回复](http://stackoverflow.com/posts/16674743/revisions)事实上,是的,写一个荒谬的东西,但对于理解什么是和不可能是非常有帮助的。关于你的问题,这是一个不适合交互式shell的较大脚本的一部分。 – AJP