如何在 Linux 命令行中检查目录是否存在?

30 linux bash command-line

如何在 Linux 命令行中检查目录是否存在?

解决方案: [ -d ¨a¨ ]&&echo ¨exists¨||echo ¨not exists¨

Ste*_*ini 41

$ if test -d /the/dir; then echo "exist"; fi 
Run Code Online (Sandbox Code Playgroud)

  • 那是命令行。您可以直接将其输入到 bash 中,也可以将其恢复为 `test -d /the/dir`:`test -d /the/dir && echo "exist" || echo "不存在"` 但它们实际上是一样的。 (6认同)

Bri*_*ter 14

假设你的 shell 是 BASH:

if [ -d /the/dir ]; then echo 'Exists'; else echo 'Not found'; fi
Run Code Online (Sandbox Code Playgroud)


Ste*_*son 9

规范的方法是使用test(1)实用程序:

test -d path && echo "Directory Exists"
Run Code Online (Sandbox Code Playgroud)

其中path是您要检查的目录的路径名。

例如:

test -d Desktop/ && echo "Directory Exists"
Directory Exists
test -d Desktop1/ && echo "Directory Exists"
# nothing appers
Run Code Online (Sandbox Code Playgroud)


小智 9

[ -d /home/bla/ ] && echo "exits"
Run Code Online (Sandbox Code Playgroud)