问题
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?
回答1:
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"
回答2:
Add some spaces:
if [ ! -d "$DIR" ]; then
# ^ ^
回答3:
You could also attempt to simply by saying:
test -d "${dir}" || mkdir "${dir}"
This would create the directory if it doesn't exist.
来源:https://stackoverflow.com/questions/18119689/command-not-found-in-bashs-if-else-condition-when-using-d-dir