只有mkdir,如果它不存在

时间:2013-09-04 20:11:06

标签: bash unix

在我的bash脚本中,我这样做:

mkdir product;

当我多次运行脚本时,我得到了:

mkdir: product: File exists

在控制台中。

所以我期待只有dir不存在才能运行mkdir。这可能吗?

5 个答案:

答案 0 :(得分:166)

做一个测试

[[ -d dir ]] || mkdir dir

或者使用-p选项:

mkdir -p dir

答案 1 :(得分:66)

if [ ! -d directory ]; then
  mkdir directory
fi

mkdir -p directory
如果-p不存在,

directory可确保创建

答案 2 :(得分:8)

使用mkdir的-p选项,但请注意它还有其他效果。

 -p      Create intermediate directories as required.  If this option is not specified, the full path prefix of each oper-
         and must already exist.  On the other hand, with this option specified, no error will be reported if a directory
         given as an operand already exists.  Intermediate directories are created with permission bits of rwxrwxrwx
         (0777) as modified by the current umask, plus write and search permission for the owner.

答案 3 :(得分:3)

mkdir -p

  

-p, - 父母                 如果存在则没有错误,根据需要创建父目录

答案 4 :(得分:2)

尝试使用: -

mkdir -p dir;

注意: - 这也会创建不存在的任何中间目录;例如,

查看mkdir -p

或试试这个: -

if [[ ! -e $dir ]]; then
    mkdir $dir
elif [[ ! -d $dir ]]; then
    echo "$Message" 1>&2
fi
相关问题