shell脚本测试目录是否存在,如果不存在则创建它?
我正在尝试创建一个脚本来检测目录是否存在,如果不存在,则创建它。
我怎样才能做到这一点?
我做了一些挖掘并发现了一个线索:
test -d directory
...将返回 true
或 false
取决于目录是否存在。
但是我如何将它与 mkdir 结合在一起呢?
I am trying to create a script to detect whether a directory exists, and if it does not, to create it.
How can I do that?
I did some digging and found a clue:
test -d directory
...will return true
or false
depending on whether the directory exists or not.
But how do I tie this together with mkdir
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
mkdir -p $directory
应该做你想要的。-p
选项将创建任何必要的父目录。如果$directory
已作为目录存在,则该命令不执行任何操作,并且会成功。如果$directory
是常规文件,它将保持不变,并且该命令将失败并显示相应的错误消息。如果没有
mkdir
的-p
选项,test ... ||如果
策略可能会失败。无论如何,$directory
包含“/”,并且该路径的某些组件尚不存在,则 mkdir ...test
都是多余的,因为mkdir
在内部进行了相同的测试。mkdir -p $directory
should do what you want. The-p
option will create any necessary parent directories. If$directory
already exists as a directory, the command does nothing, and succeeds. If$directory
is a regular file, it will remain untouched, and the command will fail with an appropriate error message.Without the
-p
option tomkdir
, thetest ... || mkdir ...
strategy can fail if$directory
contains a '/', and some component of that path doesn't already exist. Thetest
is superfluous anyway, sincemkdir
does the same test internally.