bash 使用 [! -d "$DIR"]
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18119689/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Command not found in Bash's IF-ELSE condition when using [! -d "$DIR"]
提问by neversaint
I have a code like this
我有这样的代码
#!/bin/bash
DIR="test_dir/";
if [! -d "$DIR"]; then
# If it doesn't create it
mkdir $DIR
fi
But why executing it gave me this:
但是为什么执行它给了我这个:
./mycode.sh: line 16: [!: command not found
What's the right way to do it?
正确的做法是什么?
回答by konsolebox
Add space between [ and !. And before ] as well.
在 [ 和 ! 之间添加空格。在 ] 之前也是如此。
#!/bin/bash
DIR="test_dir/";
if [ ! -d "$DIR" ]; then
# If it doesn't create it
mkdir $DIR
fi
It's also a good idea to quote your variable:
引用您的变量也是一个好主意:
mkdir "$DIR"
回答by falsetru
Add some spaces:
添加一些空格:
if [ ! -d "$DIR" ]; then
# ^ ^
回答by devnull
You could also attempt to simply by saying:
您也可以尝试简单地说:
test -d "${dir}" || mkdir "${dir}"
This would create the directory if it doesn't exist.
如果目录不存在,这将创建该目录。