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


当前回答

Git Bash+Dropbox+Windows:

其他解决方案都不适用于我的Dropbox文件夹,这很奇怪,因为我可以Git推送到Dropbox符号路径。

#!/bin/bash

dbox="~/Dropbox/"
result=0
prv=$(pwd) && eval "cd $dbox" && result=1 && cd "$prv"
echo $result

read -p "Press Enter To Continue:"

您可能也想知道如何从Bash成功导航到Dropbox。这是整个脚本。

https://pastebin.com/QF2Exmpn

其他回答

要检查多个目录,请使用以下代码:

if [ -d "$DIRECTORY1" ] && [ -d "$DIRECTORY2" ] then
    # Things to do
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";

根据Jonathan的评论:

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

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

要检查目录是否存在:

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在另一个答案中解释了这一点的原因。

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

一个衬垫:

[[ -d $Directory ]] && echo true