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


当前回答

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

其他回答

检查目录是否存在,否则创建一个:

[ -d "$DIRECTORY" ] || mkdir $DIRECTORY

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

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

这个答案被包装成一个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";

要检查目录是否存在:

if [ -d "$DIRECTORY" ]; then
  echo "$DIRECTORY does exist."
fi

要检查目录是否不存在:

if [ ! -d "$DIRECTORY" ]; then
  echo "$DIRECTORY does not exist."
fi

然而,正如JonEricson指出的,如果不考虑到指向目录的符号链接也会通过此检查,则后续命令可能无法按预期工作。例如,执行以下操作:

ln -s "$ACTUAL_DIR" "$SYMLINK"
if [ -d "$SYMLINK" ]; then 
  rmdir "$SYMLINK" 
fi

将生成错误消息:

rmdir: failed to remove `symlink': Not a directory

因此,如果后续命令需要目录,则可能需要对符号链接进行不同的处理:

if [ -d "$LINK_OR_DIR" ]; then 
  if [ -L "$LINK_OR_DIR" ]; then
    # It is a symlink!
    # Symbolic link specific commands go here.
    rm "$LINK_OR_DIR"
  else
    # It's a directory!
    # Directory command goes here.
    rmdir "$LINK_OR_DIR"
  fi
fi

特别注意用于包装变量的双引号。8jean在另一个答案中解释了这一点的原因。

如果变量包含空格或其他异常字符,则可能会导致脚本失败。

可以使用以下发现,

find . -type d -name dirname -prune -print