检查一个目录是否存在于一个shell脚本中。

时间:2022-05-03 12:19:27

What command can be used to check if a directory exists or not, within a shell script?

在shell脚本中,可以使用什么命令来检查目录是否存在?

32 个解决方案

#1


3910  

To check if a directory exists in a shell script you can use the following:

要检查在shell脚本中是否存在一个目录,您可以使用以下内容:

if [ -d "$DIRECTORY" ]; then
  # Control will enter here if $DIRECTORY exists.
fi

Or to check if a directory doesn't exist:

或者检查目录是否存在:

if [ ! -d "$DIRECTORY" ]; then
  # Control will enter here if $DIRECTORY doesn't exist.
fi

However, as Jon Ericson points out (thanks Jon), subsequent commands may not work as intended if you do not take into account that a symbolic link to a directory will also pass this check. E.g. running this:

然而,正如Jon Ericson指出的(感谢Jon),如果您没有考虑到一个指向目录的符号链接也会通过此检查,那么后续的命令可能就不会起作用了。例如,运行:

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

Will produce the error message:

将产生错误信息:

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

So symbolic links may have to be treated differently, if subsequent commands expect directories:

因此,如果后续命令期望目录:那么符号链接可能需要不同的处理方式。

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

Take particular note of the double-quotes used to wrap the variables, the reason for this is explained by 8jean in another answer.

要特别注意用来包装变量的双引号,这是由8jean在另一个答案中解释的。

If the variables contain spaces or other unusual characters it will probably cause the script to fail.

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

#2


427  

Remember to always wrap variables in double quotes when referencing them in a bash script. Kids these days grow up with the idea that they can have spaces and lots of other funny characters in their directory names. (Spaces! Back in my days, we didn't have no fancy spaces! ;))

记住,在bash脚本中引用变量时,总是用双引号括起来。现在的孩子们长大了,他们可以在自己的目录里有空间和其他有趣的字符。(空间!在我的日子里,我们没有什么特别的空间!,))

One day, one of those kids will run your script with $DIRECTORY set to "My M0viez" and your script will blow up. You don't want that. So use this.

有一天,这些孩子中的一个将会运行你的脚本,将$DIRECTORY设置为“My M0viez”,你的脚本就会被放大。你不希望这样。所以使用这个。

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

#3


196  

I find the double-bracket version of test makes writing logic tests more natural:

我发现双支架版本的测试使得编写逻辑测试更加自然:

if [[ -d "${DIRECTORY}" && ! -L "${DIRECTORY}" ]] ; then
    echo "It's a bona-fide directory"
fi

#4


186  

Note the -d test can produce some surprising results:

注意-d测试可以产生一些令人惊讶的结果:

$ ln -s tmp/ t
$ if [ -d t ]; then rmdir t; fi
rmdir: directory "t": Path component not a directory

File under: "When is a directory not a directory?" The answer: "When it's a symlink to a directory." A slightly more thorough test:

文件下:“什么时候目录不是目录?”答案是:“当它是一个目录的符号链接时。”一个稍微更彻底的测试:

if [ -d t ]; then 
   if [ -L t ]; then 
      rm t
   else 
      rmdir t
   fi
fi

You can find more information in the Bash manual on Bash conditional expressions and the [ builtin command and the [[ compound commmand.

您可以在Bash条件表达式和[builtin命令]和[[复合命令]中找到更多信息。

#5


118  

Shorter form:

短形式:

[ -d "$DIR" ] && echo "Yes"

#6


110  

To check if a directory exists you can use simple if structure like this:

为了检查目录是否存在,可以使用简单的if结构:

if [ -d directory/path to a directory ] ; then
#Things to do

else #if needed #also: elif [new condition] 
# things to do
fi

You can do it also in negative

你也可以用否定的方法来做。

if [ ! -d directory/path to a directory ] ; then
# things to do when not an existing directory

Note: Be careful, leave empty spaces on either side of both opening and closing braces.

注意:要小心,在打开和关闭牙套的两边都要留出空隙。

With the same syntax you can use:

使用相同的语法:

-e: any kind of archive 

-f: file 

-h: symbolic link 

-r: readable file 

-w: writable file 

-x: executable file 

-s: file size greater than zero 

#7


75  

if [ -d "$DIRECTORY" ]; then  
    # Here if $DIRECTORY exists  
fi

#8


66  

You can use test -d (see man test).

您可以使用test -d(见man测试)。

-d file True if file exists and is a directory.

如果文件存在并且是一个目录,则文件为真。

For example:

例如:

test -d "/etc" && echo Exists || echo Does not exist

Note: The test command is same as conditional expression [ (see: man [), so it's portable across shell scripts.

注意:测试命令与条件表达式相同[(参见:man[),因此它可以跨shell脚本移植。

[ - This is a synonym for the test builtin, but the last argument must, be a literal ], to match the opening [.

[-这是测试构建的同义词,但最后一个参数必须是文字的],以匹配开头[。

For possible options or further help, check:

对于可能的选择或进一步的帮助,请检查:

  • help [
  • 帮助
  • help test
  • 帮助测试
  • man test or man [
  • 男子测试或男子[

#9


51  

Or for something completely useless:

或者是完全无用的东西:

[ -d . ] || echo "No"

#10


45  

Here's a very pragmatic idiom:

这里有一个非常实用的习语:

(cd $dir) || return # is this a directory,
                    # and do we have access?

I typically wrap it in a function:

我通常把它包装成一个函数:

can_use_as_dir() { 
    (cd ${1:?pathname expected}) || return
}

Or:

或者:

assert_dir_access() { 
    (cd ${1:?pathname expected}) || exit
}

The nice thing about this approach is that I do not have to think of a good error message.

这种方法的好处是,我不必考虑一个好的错误消息。

cd will give me a standard one line message to stderr already. It will also give more information than I will be able to provide. By performing the cd inside a subshell ( ... ), the command does not affect the current directory of the caller. If the directory exists, this subshell and the function are just a no-op.

cd会给我一个标准的单行信息给stderr。它也会提供比我所能提供的更多的信息。通过在子shell中执行cd(…)该命令不会影响调用者的当前目录。如果目录存在,这个子shell和函数只是一个不操作。

Next is the argument that we pass to cd: ${1:?pathname expected}. This is a more elaborate form of parameter substitution which is explained in more detail below.

下面是我们传递给cd的参数:${1:?路径名}。这是一种更详细的参数替换形式,下面将对此进行更详细的解释。

Tl;dr: If the string passed into this function is empty, we again exit from the subshell ( ... ) and return from the function with the given error message.

如果传递给这个函数的字符串是空的,那么我们将再次从子shell中退出(…)并从函数返回给定的错误消息。


Quoting from the ksh93 man page:

引用ksh93手册页:

${parameter:?word}

If parameter is set and is non-null then substitute its value; otherwise, print word and exit from the shell (if not interactive). If word is omitted then a standard message is printed.

如果参数设置为非空,那么就替换它的值;否则,打印单词并退出shell(如果不是交互式的)。如果省略了单词,则会打印一条标准消息。

and

If the colon : is omitted from the above expressions, then the shell only checks whether parameter is set or not.

如果冒号:在上面的表达式中省略了,那么shell只检查参数是否设置。

The phrasing here is peculiar to the shell documentation, as word may refer to any reasonable string, including whitespace.

这里的措辞是shell文档特有的,因为word可以引用任何合理的字符串,包括空格。

In this particular case, I know that the standard error message 1: parameter not set is not sufficient, so I zoom in on the type of value that we expect here - the pathname of a directory.

在这个特殊的例子中,我知道标准错误消息1:参数not set是不够的,所以我放大了我们所期望的值的类型——目录的路径名。

A philosphical note: The shell is not an object oriented language, so the message says pathname, not directory. At this level, I'd rather keep it simple - the arguments to a function are just strings.

一个哲学注释:shell不是面向对象的语言,所以消息说的是路径名,而不是目录。在这个级别上,我宁愿保持简单——函数的参数只是字符串。

#11


33  

if [ -d "$Directory" -a -w "$Directory" ]
then
    #Statements
fi

The above code checks if the directory exists and if it is writable.

上面的代码检查目录是否存在,是否可写。

#12


23  

Type this code on the bash promt

在bash promt上键入此代码。

if [ -d "$DIRECTORY" ]; then
  # if true this block of code will execute
fi

#13


19  

Actually, you should use several tools to get a bulletproof approach:

实际上,您应该使用一些工具来获得防弹方法:

DIR_PATH=`readlink -f "${the_stuff_you_test}"` # Get rid of symlinks and get abs path
if [[ -d "${DIR_PATH}" ]] ; Then # now you're testing
    echo "It's a dir";
fi

No need to worry about spaces and special characters as long as you use "${}".

不用担心空格和特殊字符,只要使用“${}”即可。

Note that [[]] is not as portable as [], but since most people work with modern versions of Bash (since after all, most people don't even work with command line :-p), the benefit is greater than the trouble.

请注意[[]]不像[]那样可移植,但是由于大多数人都使用Bash的现代版本(毕竟,大多数人甚至不使用命令行:-p),因此好处大于麻烦。

#14


18  

More features using find

  • Check existence of the folder within sub-directories:

    检查子目录内文件夹的存在:

    found=`find -type d -name "myDirectory"`
    if [ -n "$found"]
    then
        # The variable 'found' contains the full path where "myDirectory" is.
        # It may contain several lines if there are several folders named "myDirectory".
    fi
    
  • Check existence of one or several folders based on a pattern within the current directory:

    根据当前目录中的模式检查一个或多个文件夹的存在:

    found=`find -maxdepth 1 -type d -name "my*"`
    if [ -n "$found"]
    then
        # The variable 'found' contains the full path where folders "my*" have been found.
    fi
    
  • Both combinations. In the following example, it checks the existence of the folder in the current directory:

    这两个的组合。在下面的示例中,它检查当前目录中文件夹的存在:

    found=`find -maxdepth 1 -type d -name "myDirectory"`
    if [ -n "$found"]
    then
        # The variable 'found' is not empty => "myDirectory"` exists.
    fi
    

#15


16  

To check more than one directory use this code:

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

if [ -d "$DIRECTORY1" ] && [ -d "$DIRECTORY2" ] then
    # Things to do
fi

#16


14  

[[ -d "$DIR" && ! -L "$DIR" ]] && echo "It's a directory and not a symbolic link"

N.B: Quoting variables is a good practice.

N。B:引用变量是很好的练习。

#17


13  

Check if directory exists, else make one

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

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

#18


12  

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

#19


12  

Have you considered just doing whatever you want to do in the if rather than looking before you leap?

你有没有考虑过在你想做的事情上做你想做的事情,而不是在你跳之前先看一看?

IE, if you want to check for the existence of a directory before you enter it, try just doing this:

如果您想在进入目录之前检查目录是否存在,请尝试这样做:

if pushd /path/you/want/to/enter; then
    # commands you want to run in this directory
    popd
fi

If the path you give to pushd exists, you'll enter it and it'll exit with 0, which means the then portion of the statement will execute. If it doesn't exist, nothing will happen (other than some output saying the directory doesn't exist, which is probably a helpful side-effect anyways for debugging).

如果您给pushd的路径存在,您将输入它,它将以0退出,这意味着该语句的随后部分将执行。如果它不存在,什么都不会发生(除了一些输出说目录不存在,这可能是一个有用的副作用,任何调试的方法)。

Seems better than this, which requires repeating yourself:

似乎比这更好,这需要重复你自己:

if [ -d /path/you/want/to/enter ]; then
    pushd /path/you/want/to/enter
    # commands you want to run in this directory
    popd
fi

Same thing works with cd, mv, rm, etc... if you try them on files that don't exist, they'll exit with an error and print a message saying it doesn't exist, and your then block will be skipped. If you try them on files that do exist, the command will execute and exit with a status of 0, allowing your then block to execute.

cd、mv、rm等都是一样的。如果您在不存在的文件上尝试它们,它们将会出现错误,并打印一条消息说它不存在,然后您的块将被跳过。如果您在确实存在的文件上尝试它们,则命令将以0的状态执行和退出,从而允许您的代码块执行。

#20


11  

This answer wrapped up as a shell script

这个答案被包装成一个shell脚本。

Examples

$ 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_dir

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";

#21


9  

Using the -e check will check for files and this includes directories.

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

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

#22


8  

As per Jonathan comment:

根据乔纳森·评论:

If you want to create the directory and it does not exist yet, then the simplest technique is to use mkdir -p which creates the directory — and any missing directories up the path — and does not fail if the directory already exists, so you can do it all at once with:

如果你想创建一个目录,它不存在,那么最简单的方法是使用mkdir - p创建目录——和任何缺失的目录的路径,不会失败如果目录已经存在,所以你可以做一次:

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

#23


6  

if [ -d "$DIRECTORY" ]; then
    # Will enter here if $DIRECTORY exists
fi

This is not completely true... If you want to go to that directory, you also needs to have the execute rights on the directory. Maybe you need to have write rights as well.

这不是完全正确的……如果您想要访问该目录,您还需要在目录中拥有execute权限。也许你也需要写权利。

Therfore:

所以:

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

#24


6  

The ls command in conjunction with -l (long listing) option returns attributes information about files and directories.
In particular the first character of ls -l output it is usually a d or a - (dash). In case of a d the one listed is a directory for sure.

ls命令与-l(长列表)选项一起返回关于文件和目录的属性信息。特别是ls -l输出的第一个字符通常是d或a - (dash)。如果是d,那么列出的就是一个目录。

The following command in just one line will tell you if the given ISDIR variable contains a path to a directory or not:

如果给定的ISDIR变量包含路径到目录,那么下面的命令将告诉您:

[[ $(ls -ld "$ISDIR" | cut -c1) == 'd' ]] &&
    echo "YES, $ISDIR is a directory." || 
    echo "Sorry, $ISDIR is not a directory"

Practical usage:

实际的用法:

    [claudio@nowhere ~]$ ISDIR="$HOME/Music" 
    [claudio@nowhere ~]$ ls -ld "$ISDIR"
    drwxr-xr-x. 2 claudio claudio 4096 Aug 23 00:02 /home/claudio/Music
    [claudio@nowhere ~]$ [[ $(ls -ld "$ISDIR" | cut -c1) == 'd' ]] && 
        echo "YES, $ISDIR is a directory." ||
        echo "Sorry, $ISDIR is not a directory"
    YES, /home/claudio/Music is a directory.

    [claudio@nowhere ~]$ touch "empty file.txt"
    [claudio@nowhere ~]$ ISDIR="$HOME/empty file.txt" 
    [claudio@nowhere ~]$ [[ $(ls -ld "$ISDIR" | cut -c1) == 'd' ]] && 
        echo "YES, $ISDIR is a directory." || 
        echo "Sorry, $ISDIR is not a directoy"
    Sorry, /home/claudio/empty file.txt is not a directory

#25


5  

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

#26


5  

If you want to check if a directory exists, regardless if it's a real directory or a symlink, use this:

如果您想检查一个目录是否存在,无论它是一个真正的目录还是一个符号链接,请使用以下内容:

ls $DIR
if [ $? != 0 ]; then
        echo "Directory $DIR already exists!"
        exit 1;
fi
echo "Directory $DIR does not exist..."

Explanation: The "ls" command gives an error "ls: /x: No such file or directory" if the directory or symlink does not exist, and also sets the return code, which you can retrieve via "$?", to non-null (normally "1"). Be sure that you check the return code directly after calling "ls".

说明:“ls”命令给出了一个错误“ls: /x:没有这样的文件或目录”,如果目录或符号链接不存在,并且还设置了返回代码,您可以通过“$?”检索它。,非空(通常为“1”)。请确保在调用“ls”后直接检查返回代码。

#27


5  

(1)

(1)

[ -d Piyush_Drv1 ] && echo ""Exists"" || echo "Not Exists"

(2)

(2)

[ `find . -type d -name Piyush_Drv1 -print | wc -l` -eq 1 ] && echo Exists || echo "Not Exists"

(3)

(3)

[[ -d run_dir  && ! -L run_dir ]] && echo Exists || echo "Not Exists"

If found an issue with one of the approach provided above.

如果发现一个问题与上面提供的方法之一。

With ls command; the cases when directory does not exists - an error message is shown

使用ls命令;当目录不存在时,会显示一条错误消息。

$ [[ ls -ld SAMPLE_DIR| grep ^d | wc -l -eq 1 ]] && echo exists || not exists -ksh: not: not found [No such file or directory]

美元[[ls ld SAMPLE_DIR | grep ^ d | wc - l eq 1]]& &回波存在| |不存在ksh:不是:未找到(没有这样的文件或目录)

#28


4  

Great solutions out there, but ultimately every script will fail if you're not in the right directory. So code like this:

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

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

will execute successfully only if at the moment of execution you're in a directory that has a subdirectory that you happen to check for.

只有在执行的时候,才会成功地执行,您在一个目录中,该目录中有您要检查的子目录。

I understand the initial question like this: to verify if a directory exists irrespective of the user's position in the file system. So using the command 'find' might do the trick:

我理解这样的初始问题:验证一个目录是否存在,而不考虑用户在文件系统中的位置。因此,使用“find”命令可能会奏效:

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

This solution is good because it allows the use of wildcards, a useful feature when searching for files/directories. The only problem is that, if the searched directory doesn't exist, the 'find' command will print nothing to stdout (not an elegant solution for my taste) and will have nonetheless a zero exit. Maybe someone could improve on this.

这个解决方案很好,因为它允许使用通配符,这在搜索文件/目录时很有用。唯一的问题是,如果搜索目录不存在,“find”命令将不会打印任何东西给stdout(对于我的口味来说,这不是一个优雅的解决方案),而且将会有一个零出口。也许有人可以改进一下。

#29


4  

Below find can be used,

以下是可以使用的,

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

#30


3  

Git Bash + Dropbox + Windows :

Git Bash + Dropbox + Windows:

None of the other solutions worked for my Dropbox folder, which was weird because I can git push to dropbox symbolic path.

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

#!/bin/bash

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

read -p "Press Enter To Continue:"

You'll probably want to know how to successfully navigate to dropbox from bash as well. So here is the script in it's entirity.

您可能想知道如何成功地从bash导航到dropbox。这是它的脚本。

https://pastebin.com/QF2Exmpn

https://pastebin.com/QF2Exmpn

#1


3910  

To check if a directory exists in a shell script you can use the following:

要检查在shell脚本中是否存在一个目录,您可以使用以下内容:

if [ -d "$DIRECTORY" ]; then
  # Control will enter here if $DIRECTORY exists.
fi

Or to check if a directory doesn't exist:

或者检查目录是否存在:

if [ ! -d "$DIRECTORY" ]; then
  # Control will enter here if $DIRECTORY doesn't exist.
fi

However, as Jon Ericson points out (thanks Jon), subsequent commands may not work as intended if you do not take into account that a symbolic link to a directory will also pass this check. E.g. running this:

然而,正如Jon Ericson指出的(感谢Jon),如果您没有考虑到一个指向目录的符号链接也会通过此检查,那么后续的命令可能就不会起作用了。例如,运行:

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

Will produce the error message:

将产生错误信息:

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

So symbolic links may have to be treated differently, if subsequent commands expect directories:

因此,如果后续命令期望目录:那么符号链接可能需要不同的处理方式。

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

Take particular note of the double-quotes used to wrap the variables, the reason for this is explained by 8jean in another answer.

要特别注意用来包装变量的双引号,这是由8jean在另一个答案中解释的。

If the variables contain spaces or other unusual characters it will probably cause the script to fail.

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

#2


427  

Remember to always wrap variables in double quotes when referencing them in a bash script. Kids these days grow up with the idea that they can have spaces and lots of other funny characters in their directory names. (Spaces! Back in my days, we didn't have no fancy spaces! ;))

记住,在bash脚本中引用变量时,总是用双引号括起来。现在的孩子们长大了,他们可以在自己的目录里有空间和其他有趣的字符。(空间!在我的日子里,我们没有什么特别的空间!,))

One day, one of those kids will run your script with $DIRECTORY set to "My M0viez" and your script will blow up. You don't want that. So use this.

有一天,这些孩子中的一个将会运行你的脚本,将$DIRECTORY设置为“My M0viez”,你的脚本就会被放大。你不希望这样。所以使用这个。

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

#3


196  

I find the double-bracket version of test makes writing logic tests more natural:

我发现双支架版本的测试使得编写逻辑测试更加自然:

if [[ -d "${DIRECTORY}" && ! -L "${DIRECTORY}" ]] ; then
    echo "It's a bona-fide directory"
fi

#4


186  

Note the -d test can produce some surprising results:

注意-d测试可以产生一些令人惊讶的结果:

$ ln -s tmp/ t
$ if [ -d t ]; then rmdir t; fi
rmdir: directory "t": Path component not a directory

File under: "When is a directory not a directory?" The answer: "When it's a symlink to a directory." A slightly more thorough test:

文件下:“什么时候目录不是目录?”答案是:“当它是一个目录的符号链接时。”一个稍微更彻底的测试:

if [ -d t ]; then 
   if [ -L t ]; then 
      rm t
   else 
      rmdir t
   fi
fi

You can find more information in the Bash manual on Bash conditional expressions and the [ builtin command and the [[ compound commmand.

您可以在Bash条件表达式和[builtin命令]和[[复合命令]中找到更多信息。

#5


118  

Shorter form:

短形式:

[ -d "$DIR" ] && echo "Yes"

#6


110  

To check if a directory exists you can use simple if structure like this:

为了检查目录是否存在,可以使用简单的if结构:

if [ -d directory/path to a directory ] ; then
#Things to do

else #if needed #also: elif [new condition] 
# things to do
fi

You can do it also in negative

你也可以用否定的方法来做。

if [ ! -d directory/path to a directory ] ; then
# things to do when not an existing directory

Note: Be careful, leave empty spaces on either side of both opening and closing braces.

注意:要小心,在打开和关闭牙套的两边都要留出空隙。

With the same syntax you can use:

使用相同的语法:

-e: any kind of archive 

-f: file 

-h: symbolic link 

-r: readable file 

-w: writable file 

-x: executable file 

-s: file size greater than zero 

#7


75  

if [ -d "$DIRECTORY" ]; then  
    # Here if $DIRECTORY exists  
fi

#8


66  

You can use test -d (see man test).

您可以使用test -d(见man测试)。

-d file True if file exists and is a directory.

如果文件存在并且是一个目录,则文件为真。

For example:

例如:

test -d "/etc" && echo Exists || echo Does not exist

Note: The test command is same as conditional expression [ (see: man [), so it's portable across shell scripts.

注意:测试命令与条件表达式相同[(参见:man[),因此它可以跨shell脚本移植。

[ - This is a synonym for the test builtin, but the last argument must, be a literal ], to match the opening [.

[-这是测试构建的同义词,但最后一个参数必须是文字的],以匹配开头[。

For possible options or further help, check:

对于可能的选择或进一步的帮助,请检查:

  • help [
  • 帮助
  • help test
  • 帮助测试
  • man test or man [
  • 男子测试或男子[

#9


51  

Or for something completely useless:

或者是完全无用的东西:

[ -d . ] || echo "No"

#10


45  

Here's a very pragmatic idiom:

这里有一个非常实用的习语:

(cd $dir) || return # is this a directory,
                    # and do we have access?

I typically wrap it in a function:

我通常把它包装成一个函数:

can_use_as_dir() { 
    (cd ${1:?pathname expected}) || return
}

Or:

或者:

assert_dir_access() { 
    (cd ${1:?pathname expected}) || exit
}

The nice thing about this approach is that I do not have to think of a good error message.

这种方法的好处是,我不必考虑一个好的错误消息。

cd will give me a standard one line message to stderr already. It will also give more information than I will be able to provide. By performing the cd inside a subshell ( ... ), the command does not affect the current directory of the caller. If the directory exists, this subshell and the function are just a no-op.

cd会给我一个标准的单行信息给stderr。它也会提供比我所能提供的更多的信息。通过在子shell中执行cd(…)该命令不会影响调用者的当前目录。如果目录存在,这个子shell和函数只是一个不操作。

Next is the argument that we pass to cd: ${1:?pathname expected}. This is a more elaborate form of parameter substitution which is explained in more detail below.

下面是我们传递给cd的参数:${1:?路径名}。这是一种更详细的参数替换形式,下面将对此进行更详细的解释。

Tl;dr: If the string passed into this function is empty, we again exit from the subshell ( ... ) and return from the function with the given error message.

如果传递给这个函数的字符串是空的,那么我们将再次从子shell中退出(…)并从函数返回给定的错误消息。


Quoting from the ksh93 man page:

引用ksh93手册页:

${parameter:?word}

If parameter is set and is non-null then substitute its value; otherwise, print word and exit from the shell (if not interactive). If word is omitted then a standard message is printed.

如果参数设置为非空,那么就替换它的值;否则,打印单词并退出shell(如果不是交互式的)。如果省略了单词,则会打印一条标准消息。

and

If the colon : is omitted from the above expressions, then the shell only checks whether parameter is set or not.

如果冒号:在上面的表达式中省略了,那么shell只检查参数是否设置。

The phrasing here is peculiar to the shell documentation, as word may refer to any reasonable string, including whitespace.

这里的措辞是shell文档特有的,因为word可以引用任何合理的字符串,包括空格。

In this particular case, I know that the standard error message 1: parameter not set is not sufficient, so I zoom in on the type of value that we expect here - the pathname of a directory.

在这个特殊的例子中,我知道标准错误消息1:参数not set是不够的,所以我放大了我们所期望的值的类型——目录的路径名。

A philosphical note: The shell is not an object oriented language, so the message says pathname, not directory. At this level, I'd rather keep it simple - the arguments to a function are just strings.

一个哲学注释:shell不是面向对象的语言,所以消息说的是路径名,而不是目录。在这个级别上,我宁愿保持简单——函数的参数只是字符串。

#11


33  

if [ -d "$Directory" -a -w "$Directory" ]
then
    #Statements
fi

The above code checks if the directory exists and if it is writable.

上面的代码检查目录是否存在,是否可写。

#12


23  

Type this code on the bash promt

在bash promt上键入此代码。

if [ -d "$DIRECTORY" ]; then
  # if true this block of code will execute
fi

#13


19  

Actually, you should use several tools to get a bulletproof approach:

实际上,您应该使用一些工具来获得防弹方法:

DIR_PATH=`readlink -f "${the_stuff_you_test}"` # Get rid of symlinks and get abs path
if [[ -d "${DIR_PATH}" ]] ; Then # now you're testing
    echo "It's a dir";
fi

No need to worry about spaces and special characters as long as you use "${}".

不用担心空格和特殊字符,只要使用“${}”即可。

Note that [[]] is not as portable as [], but since most people work with modern versions of Bash (since after all, most people don't even work with command line :-p), the benefit is greater than the trouble.

请注意[[]]不像[]那样可移植,但是由于大多数人都使用Bash的现代版本(毕竟,大多数人甚至不使用命令行:-p),因此好处大于麻烦。

#14


18  

More features using find

  • Check existence of the folder within sub-directories:

    检查子目录内文件夹的存在:

    found=`find -type d -name "myDirectory"`
    if [ -n "$found"]
    then
        # The variable 'found' contains the full path where "myDirectory" is.
        # It may contain several lines if there are several folders named "myDirectory".
    fi
    
  • Check existence of one or several folders based on a pattern within the current directory:

    根据当前目录中的模式检查一个或多个文件夹的存在:

    found=`find -maxdepth 1 -type d -name "my*"`
    if [ -n "$found"]
    then
        # The variable 'found' contains the full path where folders "my*" have been found.
    fi
    
  • Both combinations. In the following example, it checks the existence of the folder in the current directory:

    这两个的组合。在下面的示例中,它检查当前目录中文件夹的存在:

    found=`find -maxdepth 1 -type d -name "myDirectory"`
    if [ -n "$found"]
    then
        # The variable 'found' is not empty => "myDirectory"` exists.
    fi
    

#15


16  

To check more than one directory use this code:

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

if [ -d "$DIRECTORY1" ] && [ -d "$DIRECTORY2" ] then
    # Things to do
fi

#16


14  

[[ -d "$DIR" && ! -L "$DIR" ]] && echo "It's a directory and not a symbolic link"

N.B: Quoting variables is a good practice.

N。B:引用变量是很好的练习。

#17


13  

Check if directory exists, else make one

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

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

#18


12  

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

#19


12  

Have you considered just doing whatever you want to do in the if rather than looking before you leap?

你有没有考虑过在你想做的事情上做你想做的事情,而不是在你跳之前先看一看?

IE, if you want to check for the existence of a directory before you enter it, try just doing this:

如果您想在进入目录之前检查目录是否存在,请尝试这样做:

if pushd /path/you/want/to/enter; then
    # commands you want to run in this directory
    popd
fi

If the path you give to pushd exists, you'll enter it and it'll exit with 0, which means the then portion of the statement will execute. If it doesn't exist, nothing will happen (other than some output saying the directory doesn't exist, which is probably a helpful side-effect anyways for debugging).

如果您给pushd的路径存在,您将输入它,它将以0退出,这意味着该语句的随后部分将执行。如果它不存在,什么都不会发生(除了一些输出说目录不存在,这可能是一个有用的副作用,任何调试的方法)。

Seems better than this, which requires repeating yourself:

似乎比这更好,这需要重复你自己:

if [ -d /path/you/want/to/enter ]; then
    pushd /path/you/want/to/enter
    # commands you want to run in this directory
    popd
fi

Same thing works with cd, mv, rm, etc... if you try them on files that don't exist, they'll exit with an error and print a message saying it doesn't exist, and your then block will be skipped. If you try them on files that do exist, the command will execute and exit with a status of 0, allowing your then block to execute.

cd、mv、rm等都是一样的。如果您在不存在的文件上尝试它们,它们将会出现错误,并打印一条消息说它不存在,然后您的块将被跳过。如果您在确实存在的文件上尝试它们,则命令将以0的状态执行和退出,从而允许您的代码块执行。

#20


11  

This answer wrapped up as a shell script

这个答案被包装成一个shell脚本。

Examples

$ 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_dir

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";

#21


9  

Using the -e check will check for files and this includes directories.

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

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

#22


8  

As per Jonathan comment:

根据乔纳森·评论:

If you want to create the directory and it does not exist yet, then the simplest technique is to use mkdir -p which creates the directory — and any missing directories up the path — and does not fail if the directory already exists, so you can do it all at once with:

如果你想创建一个目录,它不存在,那么最简单的方法是使用mkdir - p创建目录——和任何缺失的目录的路径,不会失败如果目录已经存在,所以你可以做一次:

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

#23


6  

if [ -d "$DIRECTORY" ]; then
    # Will enter here if $DIRECTORY exists
fi

This is not completely true... If you want to go to that directory, you also needs to have the execute rights on the directory. Maybe you need to have write rights as well.

这不是完全正确的……如果您想要访问该目录,您还需要在目录中拥有execute权限。也许你也需要写权利。

Therfore:

所以:

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

#24


6  

The ls command in conjunction with -l (long listing) option returns attributes information about files and directories.
In particular the first character of ls -l output it is usually a d or a - (dash). In case of a d the one listed is a directory for sure.

ls命令与-l(长列表)选项一起返回关于文件和目录的属性信息。特别是ls -l输出的第一个字符通常是d或a - (dash)。如果是d,那么列出的就是一个目录。

The following command in just one line will tell you if the given ISDIR variable contains a path to a directory or not:

如果给定的ISDIR变量包含路径到目录,那么下面的命令将告诉您:

[[ $(ls -ld "$ISDIR" | cut -c1) == 'd' ]] &&
    echo "YES, $ISDIR is a directory." || 
    echo "Sorry, $ISDIR is not a directory"

Practical usage:

实际的用法:

    [claudio@nowhere ~]$ ISDIR="$HOME/Music" 
    [claudio@nowhere ~]$ ls -ld "$ISDIR"
    drwxr-xr-x. 2 claudio claudio 4096 Aug 23 00:02 /home/claudio/Music
    [claudio@nowhere ~]$ [[ $(ls -ld "$ISDIR" | cut -c1) == 'd' ]] && 
        echo "YES, $ISDIR is a directory." ||
        echo "Sorry, $ISDIR is not a directory"
    YES, /home/claudio/Music is a directory.

    [claudio@nowhere ~]$ touch "empty file.txt"
    [claudio@nowhere ~]$ ISDIR="$HOME/empty file.txt" 
    [claudio@nowhere ~]$ [[ $(ls -ld "$ISDIR" | cut -c1) == 'd' ]] && 
        echo "YES, $ISDIR is a directory." || 
        echo "Sorry, $ISDIR is not a directoy"
    Sorry, /home/claudio/empty file.txt is not a directory

#25


5  

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

#26


5  

If you want to check if a directory exists, regardless if it's a real directory or a symlink, use this:

如果您想检查一个目录是否存在,无论它是一个真正的目录还是一个符号链接,请使用以下内容:

ls $DIR
if [ $? != 0 ]; then
        echo "Directory $DIR already exists!"
        exit 1;
fi
echo "Directory $DIR does not exist..."

Explanation: The "ls" command gives an error "ls: /x: No such file or directory" if the directory or symlink does not exist, and also sets the return code, which you can retrieve via "$?", to non-null (normally "1"). Be sure that you check the return code directly after calling "ls".

说明:“ls”命令给出了一个错误“ls: /x:没有这样的文件或目录”,如果目录或符号链接不存在,并且还设置了返回代码,您可以通过“$?”检索它。,非空(通常为“1”)。请确保在调用“ls”后直接检查返回代码。

#27


5  

(1)

(1)

[ -d Piyush_Drv1 ] && echo ""Exists"" || echo "Not Exists"

(2)

(2)

[ `find . -type d -name Piyush_Drv1 -print | wc -l` -eq 1 ] && echo Exists || echo "Not Exists"

(3)

(3)

[[ -d run_dir  && ! -L run_dir ]] && echo Exists || echo "Not Exists"

If found an issue with one of the approach provided above.

如果发现一个问题与上面提供的方法之一。

With ls command; the cases when directory does not exists - an error message is shown

使用ls命令;当目录不存在时,会显示一条错误消息。

$ [[ ls -ld SAMPLE_DIR| grep ^d | wc -l -eq 1 ]] && echo exists || not exists -ksh: not: not found [No such file or directory]

美元[[ls ld SAMPLE_DIR | grep ^ d | wc - l eq 1]]& &回波存在| |不存在ksh:不是:未找到(没有这样的文件或目录)

#28


4  

Great solutions out there, but ultimately every script will fail if you're not in the right directory. So code like this:

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

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

will execute successfully only if at the moment of execution you're in a directory that has a subdirectory that you happen to check for.

只有在执行的时候,才会成功地执行,您在一个目录中,该目录中有您要检查的子目录。

I understand the initial question like this: to verify if a directory exists irrespective of the user's position in the file system. So using the command 'find' might do the trick:

我理解这样的初始问题:验证一个目录是否存在,而不考虑用户在文件系统中的位置。因此,使用“find”命令可能会奏效:

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

This solution is good because it allows the use of wildcards, a useful feature when searching for files/directories. The only problem is that, if the searched directory doesn't exist, the 'find' command will print nothing to stdout (not an elegant solution for my taste) and will have nonetheless a zero exit. Maybe someone could improve on this.

这个解决方案很好,因为它允许使用通配符,这在搜索文件/目录时很有用。唯一的问题是,如果搜索目录不存在,“find”命令将不会打印任何东西给stdout(对于我的口味来说,这不是一个优雅的解决方案),而且将会有一个零出口。也许有人可以改进一下。

#29


4  

Below find can be used,

以下是可以使用的,

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

#30


3  

Git Bash + Dropbox + Windows :

Git Bash + Dropbox + Windows:

None of the other solutions worked for my Dropbox folder, which was weird because I can git push to dropbox symbolic path.

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

#!/bin/bash

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

read -p "Press Enter To Continue:"

You'll probably want to know how to successfully navigate to dropbox from bash as well. So here is the script in it's entirity.

您可能想知道如何成功地从bash导航到dropbox。这是它的脚本。

https://pastebin.com/QF2Exmpn

https://pastebin.com/QF2Exmpn