什么命令检查Bash shell脚本中是否存在目录?


当前回答

根据Jonathan的评论:

如果您想创建目录,但它还不存在,那么最简单的方法是使用mkdir-p创建目录-以及路径上的任何缺失目录-如果目录已经存在,则不会失败,因此您可以使用以下方法一次性完成:

mkdir -p /some/directory/you/want/to/exist || exit 1

其他回答

如果要检查目录是否存在,无论它是真实目录还是符号链接,请使用以下命令:

ls $DIR
if [ $? != 0 ]; then
        echo "Directory $DIR already exists!"
        exit 1;
fi
echo "Directory $DIR does not exist..."

解释:如果目录或符号链接不存在,则“ls”命令会给出错误“ls:/x:No such file or directory”,并将返回代码设置为非空(通常为“1”),您可以通过“$?”检索该代码。请确保在调用“ls”后直接检查返回代码。

if [ -d "$DIRECTORY" ]; then
    # Will enter here if $DIRECTORY exists
fi

这不是完全正确的。。。

如果要转到该目录,还需要具有该目录的执行权限。也许你也需要写权限。

因此:

if [ -d "$DIRECTORY" ] && [ -x "$DIRECTORY" ] ; then
    # ... to go to that directory (even if DIRECTORY is a link)
    cd $DIRECTORY
    pwd
fi

if [ -d "$DIRECTORY" ] && [ -w "$DIRECTORY" ] ; then
    # ... to go to that directory and write something there (even if DIRECTORY is a link)
    cd $DIRECTORY
    touch foobar
fi

您可以使用test-d(参见man test)。

-d file如果文件存在并且是目录,则为True。

例如:

test -d "/etc" && echo Exists || echo Does not exist

注意:测试命令与条件表达式[(参见:man[)相同,因此它可以跨shell脚本移植。

[-这是测试内置的同义词,但最后一个参数必须是文字],以匹配开头[。

有关可能的选项或进一步帮助,请检查:

帮助[帮助测试人工测试或人工[

这个答案被包装成一个shell脚本

示例

$ is_dir ~                           
YES

$ is_dir /tmp                        
YES

$ is_dir ~/bin                       
YES

$ mkdir '/tmp/test me'

$ is_dir '/tmp/test me'
YES

$ is_dir /asdf/asdf                  
NO

# Example of calling it in another script
DIR=~/mydata
if [ $(is_dir $DIR) == "NO" ]
then
  echo "Folder doesnt exist: $DIR";
  exit;
fi

is目录

function show_help()
{
  IT=$(CAT <<EOF

  usage: DIR
  output: YES or NO, depending on whether or not the directory exists.

  )
  echo "$IT"
  exit
}

if [ "$1" == "help" ]
then
  show_help
fi
if [ -z "$1" ]
then
  show_help
fi

DIR=$1
if [ -d $DIR ]; then 
   echo "YES";
   exit;
fi
echo "NO";

使用-e检查将检查文件,其中包括目录。

if [ -e ${FILE_PATH_AND_NAME} ]
then
    echo "The file or directory exists."
fi