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

时间:2012-03-09 13:58:41

标签: bash

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

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

但是当我跑步时,我得到了:

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

我做错了什么?

4 个答案:

答案 0 :(得分:10)

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

if [ -e file.txt ] ; then

那就是说,我推荐[[ ]] - 它在某些方面更安全(虽然它仍然需要空格):

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

答案 1 :(得分:2)

if [ -e file.txt ]; then

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

答案 2 :(得分:2)

Woops,结果我需要[-e之间的空格。像这样:

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

答案 3 :(得分:0)

'''和']'需要'自己',即被空格包围。

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