`if [-e file.txt]` 在 bash 中不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9635208/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 01:45:00  来源:igfitidea点击:

`if [-e file.txt]` not working in bash

bash

提问by Eddy

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

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

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

What am I doing wrong?

我究竟做错了什么?

回答by ruakh

[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 ]:

[不是 Bash 中的特殊标记;只是这个[是一个内置命令(就像echo)。所以你需要一个空格。而且,类似地,您在 之前需要一个空格]

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

回答by jacekmigacz

if [ -e file.txt ]; then

You need spaces. [and ]are regular programs.

你需要空格。 []是常规程序。

回答by Eddy

Woops, turns out I needed a space between [and -e. Like this:

糟糕,原来我需要在[和之间留一个空格-e。像这样:

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

回答by shellter

the '[' and ']' needs to be 'on--their-own', i.e. surrounded by spaces.

'[' 和 ']' 需要是 'on--they-own',即被空格包围。

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