Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Linux 在Bash';使用[!-d“DIR”时的s IF-ELSE条件_Linux_Bash_Unix_Directory - Fatal编程技术网

Linux 在Bash';使用[!-d“DIR”时的s IF-ELSE条件

Linux 在Bash';使用[!-d“DIR”时的s IF-ELSE条件,linux,bash,unix,directory,Linux,Bash,Unix,Directory,我有这样的代码 #!/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 正确的方法是什么?在[and!.and before]之间添加空格 #!/bin/bash DIR="test_dir/"; if [ ! -d "$DIR"

我有这样的代码

#!/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

正确的方法是什么?

在[and!.and before]之间添加空格

#!/bin/bash 
DIR="test_dir/";
if [ ! -d "$DIR" ]; then
    # If it doesn't create it
    mkdir $DIR
fi
引用变量也是一个好主意:

    mkdir "$DIR"
添加一些空格:

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

你也可以简单地说:

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

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

名称
[
是命令名,而不是随机标点符号。正如在
cat/etc/passwd
中需要
cat
/etc/passwd
之间留一个空格一样,您也需要
[
(命令名)和
(它的一个参数)之间留一个空格。同样,最后一个参数必须是
]
。这一要求可以追溯到古代历史(第7版)™ 大约在1978年或更早),当时shell没有内置的
测试
(aka
[
),唯一的
测试
命令是
/bin/test
及其(硬)链接
/bin/[/code>。或者更简单的是:
mkdir-p“$DIR”
(使用问题中的大写名称)。这将创建路径上所需的所有目录,但如果该目录已存在,则会成功。@JonathanLeffler是的,
mkdir-p foo
本身不会造成任何伤害。