shell脚本测试目录是否存在,如果不存在则创建它?

发布于 2024-09-03 15:19:05 字数 225 浏览 1 评论 0原文

我正在尝试创建一个脚本来检测目录是否存在,如果不存在,则创建它。

我怎样才能做到这一点?

我做了一些挖掘并发现了一个线索:

test -d directory

...将返回 truefalse 取决于目录是否存在。

但是我如何将它与 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

不知所踪 2024-09-10 15:19:05

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 to mkdir, the test ... || mkdir ... strategy can fail if $directory contains a '/', and some component of that path doesn't already exist. The test is superfluous anyway, since mkdir does the same test internally.

笛声青案梦长安 2024-09-10 15:19:05
test ... || mkdir ...
test ... || mkdir ...
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文