如何在linux中检查目录是否存在?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8790515/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 03:59:36  来源:igfitidea点击:

How to check directory exist or not in linux.?

linuxshell

提问by Vivek

Given a file path (e.g. /src/com/mot), how can I check whether motexists, and create it if it doesn't using Linux or shell scripting??

给定文件路径(例如/src/com/mot),如何检查是否mot存在,如果不使用 Linux 或 shell 脚本,如何创建它?

采纳答案by Chris J

With bash/sh/ksh, you can do:

使用 bash/sh/ksh,您可以执行以下操作:

if [ ! -d /directory/to/check ]; then
    mkdir -p /directory/toc/check
fi

For files, replace -dwith -f, then you can do whatever operations you need on the non-existant file.

对于文件,替换-d-f,然后您可以对不存在的文件进行任何您需要的操作。

回答by Eugen Rieck

test -d /src/com/mot || mkdir /src/com/mot

回答by Sjoerd

mkdir -pcreates the directory without giving an error if it already exists.

mkdir -p如果目录已经存在,则创建目录而不给出错误。

回答by parapura rajkumar

Check for directory exists

检查目录是否存在

if [ -d "$DIRPATH" ]; then
    # Add code logic here 
fi

Check for directory does not exist

检查目录不存在

if [ ! -d "$DIRPATH" ]; then
    # Add code logic here
fi

回答by Christian.K

Well, if you only check for the directory to create it if it does not exist, you might as well just use:

好吧,如果您只检查目录以创建它(如果它不存在),您不妨使用:

mkdir -p /src/com/mot

mkdir -pwill create the directory if it does not exist, otherwise does nothing.

mkdir -p如果目录不存在,则创建该目录,否则不执行任何操作。

回答by Silvertiger

This is baisc, but I think it works. You'll have to set a few variables if you're looking to have a dynamic list to cycle through and check.

这是 baisc,但我认为它有效。如果您希望有一个动态列表来循环和检查,则必须设置一些变量。

if [ -d /src/com/mot ];
then
    echo Directory found
else
    mkdir /src/com/mot
fi

Hope that's what you were looking for...

希望这就是你要找的...