【问题标题】:`if [-e file.txt]` not working in bash`if [-e file.txt]` 在 bash 中不起作用
【发布时间】:2012-03-09 13:58:41
【问题描述】:

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

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

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

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

我做错了什么?

【问题讨论】:

    标签: bash


    【解决方案1】:

    [ 不是 Bash 中的特殊标记;只是 word [ 是一个内置命令(就像 echo 一样)。所以你需要一个空格。同样,] 之前需要一个空格:

    if [ -e file.txt ] ; then
    

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

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

    【讨论】:

    • +1。请注意 [[ 是 bash 功能,因此您不能使用 /bin/sh 调用脚本
    • 能否编辑您的答案以解释为什么双方括号更安全?
    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:
      if [ -e file.txt ]; then
      

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

      【讨论】:

      • 学究起来,] 不是程序,它是[ 命令所需的最后一个参数
      【解决方案4】:

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

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

      【讨论】:

        猜你喜欢
        • 2020-05-19
        • 1970-01-01
        • 2010-09-24
        • 1970-01-01
        • 1970-01-01
        • 2014-06-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多