使用[时,在Bash的IF-ELSE条件下找不到命令!-d"$ DIR"]

nev*_*int 9 unix linux directory bash

我有这样的代码

#!/bin/bash 
DIR="test_dir/";
if [! -d "$DIR"]; then
    # If it doesn't create it
    mkdir $DIR
fi
Run Code Online (Sandbox Code Playgroud)

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

./mycode.sh: line 16: [!: command not found
Run Code Online (Sandbox Code Playgroud)

什么是正确的方法呢?

kon*_*box 22

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

#!/bin/bash 
DIR="test_dir/";
if [ ! -d "$DIR" ]; then
    # If it doesn't create it
    mkdir $DIR
fi
Run Code Online (Sandbox Code Playgroud)

引用变量也是个好主意:

    mkdir "$DIR"
Run Code Online (Sandbox Code Playgroud)


fal*_*tru 9

添加一些空格:

if [ ! -d "$DIR" ]; then
#   ^           ^
Run Code Online (Sandbox Code Playgroud)