【问题标题】:Command not found in Bash's IF-ELSE condition when using [! -d "$DIR"]使用 [! -d "$DIR"]
【发布时间】:2013-08-09 19:00:22
【问题描述】:

我有这样的代码

#!/bin/bash 
DIR="test_dir/";
if [! -d "$DIR"]; then
    # If it doesn't create it
    mkdir $DIR
fi

但是为什么执行它给了我这个:

./mycode.sh: line 16: [!: command not found

正确的做法是什么?

【问题讨论】:

  • 名称[是命令的名称,不是随机的标点符号。正如您需要在cat/etc/passwd 中的cat/etc/passwd 之间有一个空格一样,您也需要在[(命令名称)和!(它的参数之一)之间有一个空格。同样,最后一个参数必须是]。当 shell 没有内置 test(又名 [)并且唯一的 test 命令是 /bin/test 及其(硬)链接/bin/[.

标签: linux bash unix directory


【解决方案1】:

在 [ 和 ! 之间添加空格。在 ] 之前也是如此。

#!/bin/bash 
DIR="test_dir/";
if [ ! -d "$DIR" ]; then
    # If it doesn't create it
    mkdir $DIR
fi

引用变量也是一个好主意:

    mkdir "$DIR"

【讨论】:

    【解决方案2】:

    添加一些空格:

    if [ ! -d "$DIR" ]; then
    #   ^           ^
    

    【讨论】:

      【解决方案3】:

      您也可以尝试简单地说:

      test -d "${dir}" || mkdir "${dir}"
      

      如果目录不存在,这将创建目录。

      【讨论】:

      • 或者,更简单:mkdir -p "$DIR"(使用问题中的大写名称)。这将创建路径上所需的所有目录,但如果目录已存在则成功。
      • @JonathanLeffler 是的,mkdir -p foo 本身不会造成任何伤害。
      猜你喜欢
      • 1970-01-01
      • 2010-11-22
      • 2011-05-30
      • 2015-01-05
      • 2020-07-05
      • 2018-01-07
      • 2021-01-20
      • 1970-01-01
      • 2014-05-10
      相关资源
      最近更新 更多