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


当前回答

file="foo" 
if [[ -e "$file" ]]; then echo "File Exists"; fi;

其他回答

在三元形式中,

[ -d "$directory" ] && echo "exist" || echo "not exist"

通过测试:

test -d "$directory" && echo "exist" || echo "not exist"

测试目录或文件是否存在的简单脚本:if[-d/home/ram/dir]#对于文件“if[-f/home/rama/file]”然后echo“目录存在”其他的echo“目录不存在”传真检查目录是否存在的简单脚本:mkdir tempdir#如果要检查文件,请使用touch而不是mkdirret=$?如果[“$ret”==“0”]然后echo“目录存在”其他的echo“目录不存在”传真以上脚本将检查目录是否存在$? 如果最后一个命令成功,则返回“0”,否则返回非零值。假设tempdir已经存在。然后mkdir tempdir将给出如下错误:mkdir:无法创建目录“tempdir”:文件存在

[ -d ~/Desktop/TEMPORAL/ ] && echo "DIRECTORY EXISTS" || echo "DIRECTORY DOES NOT EXIST"

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

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

[ -d . ] || echo "No"