如果[-e file.txt]在bash中不起作用 [英] `if [-e file.txt]` not working in bash

查看:76
本文介绍了如果[-e file.txt]在bash中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用bash检查文件是否存在.这是我的代码

I'm trying to check if a file exists using bash. This is my code

if [-e file.txt]; then
  echo "file exists"
else
  echo "file doesn't exist"
fi

但是当我运行它时,我得到:

But when I run it I get:

./test.sh: line 3: [-e: command not found

我在做什么错了?

推荐答案

[在Bash中不是特殊标记;只是 word [是内置命令(就像echo一样).因此,您需要在其后留一个空间.而且,类似地,您在]之前需要一个空格:

[ is not a special token in Bash; it's just that the word [ is a builtin command (just like echo). So you need a space after it. And, similarly, you need a space before ]:

if [ -e file.txt ] ; then

也就是说,我建议使用[[ ]]而不是—在某些方面更安全(尽管仍然需要空格):

That said, I recommend [[ ]] instead — it's safer in a few ways (though it still requires the spaces):

if [[ -e file.txt ]] ; then

这篇关于如果[-e file.txt]在bash中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆