【问题标题】:Only mkdir if it does not exist [duplicate]只有 mkdir 如果它不存在 [重复]
【发布时间】:2013-09-08 11:53:54
【问题描述】:

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

mkdir product;

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

mkdir: product: File exists

在控制台中。

所以我希望只在目录不存在时运行 mkdir。这可能吗?

【问题讨论】:

  • mkdir 产品 2>/dev/null

标签: bash unix


【解决方案1】:
if [ ! -d directory ]; then
  mkdir directory
fi

或

mkdir -p directory

-p 确保在 directory 不存在时创建

【讨论】:

  • 单线需要一个额外的;:if [ ! -d directory ]; then mkdir directory; fi
【解决方案2】:

试试这个:-

mkdir -p dir;

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

查看mkdir -p

或者试试这个:-

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

【讨论】:

  • 仅供参考:-e 代表“文件存在”,-d 代表“是一个目录”
【解决方案3】:

使用 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.

【讨论】:

    【解决方案4】:

    mkdir -p

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

    【讨论】:

      【解决方案5】:

      做个测试

      [[ -d dir ]] || mkdir dir
      

      或者使用 -p 选项:

      mkdir -p dir
      

      【讨论】:

      • 我无法即时找到源代码,但不鼓励使用 Makefiles mkdir -p b/c 在并发执行中可能存在竞争条件。因此,根据您的脚本的作用以及它所处的环境,给出的第一个选项是这个答案应该是首选。此外,您可以只 mkdir product 2>/dev/null 而不在乎。
      • @user1129682:第一个选项也有潜在的竞争条件;该目录可以由-d 测试和mkdir 之间的某个其他进程创建。我怀疑mkdir -p 会使这个比赛条件的时间窗口稍微短一些。
      • 除了不必要的测试中的竞争条件之外,dir 也有可能确实存在 但不是目录,而是文件或设备条目或unix 域套接字或命名管道,或 whatever ...
      • @wildplasser 是的,这已经是编码员的选择,他/她将如何处理这种情况。如果[[ -e dir && ! -d dir ]] 有效,则可以向用户发送消息并要求输入、中止或执行其他操作。
      • 实用且简洁,+1 :)
      猜你喜欢
      • 1970-01-01
      • 2016-10-22
      • 2020-07-22
      • 1970-01-01
      • 2021-04-19
      • 2018-02-15
      • 2012-10-02
      • 2021-09-08
      • 2017-11-22
      相关资源
      最近更新 更多