什么命令检查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

其他回答

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

更多功能使用查找

检查子目录中是否存在文件夹:find=`find-type d-name“myDirectory”`如果[-n“$found”]然后#变量“find”包含“myDirectory”所在的完整路径。#如果有多个名为“myDirectory”的文件夹,它可能包含多行。传真根据当前目录中的模式检查是否存在一个或多个文件夹:found=`find-maxdepth 1-type d-name“my*”`如果[-n“$found”]然后#变量“find”包含找到文件夹“my*”的完整路径。传真两种组合。在以下示例中,它检查当前目录中是否存在文件夹:find=`find-maxdeph 1-type d-name“myDirectory”`如果[-n“$found”]然后#变量'found'不为空=>“myDirectory”`存在。传真

作为“[-d]”和“[-h]”选项的替代,您可以使用stat获取文件类型并对其进行分析。

#! /bin/bash
MY_DIR=$1
NODE_TYPE=$(stat -c '%F' ${MY_DIR} 2>/dev/null)
case "${NODE_TYPE}" in
        "directory") echo $MY_DIR;;
    "symbolic link") echo $(readlink $MY_DIR);;
                 "") echo "$MY_DIR does not exist";;
                  *) echo "$NODE_TYPE is unsupported";;
esac
exit 0

测试数据:

$ mkdir tmp
$ ln -s tmp derp
$ touch a.txt
$ ./dir.sh tmp
tmp
$ ./dir.sh derp
tmp
$ ./dir.sh a.txt
regular file is unsupported
$ ./dir.sh god
god does not exist

在Bash脚本中引用变量时,始终将变量括在双引号中。

if [ -d "$DIRECTORY" ]; then
    # Will enter here if $DIRECTORY exists, even if it contains spaces
fi

现在的孩子们在他们的目录名中添加空格和许多其他有趣的字符。(空间!在我的时代,我们没有花哨的空间!)有一天,这些孩子中的一个会运行你的脚本,$DIRECTORY设置为“My M0viez”,你的脚本就会崩溃。你不想这样。所以使用双引号。

可以使用以下发现,

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