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


当前回答

一个衬垫:

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

其他回答

使用文件程序。考虑到所有目录也是Linux中的文件,发出以下命令就足够了:

文件$directory_name

检查不存在的文件:文件blah

输出:无法打开“blah”(没有这样的文件或目录)

检查现有目录:文件bluh

输出:bluh:目录

有很多很好的解决方案,但如果您不在正确的目录中,最终每个脚本都会失败。所以代码如下:

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

只有在执行时,您所在的目录中恰好有一个子目录,您才能成功执行。

我理解这样的初始问题:无论用户在文件系统中的位置如何,都要验证目录是否存在。因此,使用命令“find”可能会奏效:

dir=" "
echo "Input directory name to search for:"
read dir
find $HOME -name $dir -type d

此解决方案很好,因为它允许使用通配符,这是搜索文件/目录时的一个有用功能。唯一的问题是,如果搜索到的目录不存在,“find”命令将不会将任何内容打印到标准输出中(对我来说这不是一个优雅的解决方案),但仍然会有一个零出口。也许有人可以改进一下。

或者对于完全无用的东西:

[ -d . ] || echo "No"
file="foo" 
if [[ -e "$file" ]]; then echo "File 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";