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
本身不会造成任何伤害。