简体   繁体   English

如何检查目录是否存在于 Bash shell 脚本中?

[英]How do I check if a directory exists in a Bash shell script?

What command checks if a directory exists or not within a Bash shell script?什么命令检查目录是否存在于 Bash shell 脚本中?

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, 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.但是,正如Jon Ericson指出的那样,如果您不考虑到目录的符号链接也将通过此检查,则后续命令可能无法按预期工作。 Eg running this:例如运行这个:

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.如果变量包含空格或其他异常字符,则可能会导致脚本失败。

Remember to always wrap variables in double quotes when referencing them in a Bash script.在 Bash 脚本中引用变量时,请记住始终将变量用双引号括起来。 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! ;)) (空间!回到我的时代,我们没有花哨的空间!;))

One day, one of those kids will run your script with $DIRECTORY set to "My M0viez" and your script will blow up.有一天,其中一个孩子会运行你的脚本,并将$DIRECTORY设置为"My M0viez" ,然后你的脚本就会崩溃。 You don't want that.你不想要那个。 So use this.所以用这个。

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

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 手册中找到有关Bash 条件表达式以及[内置命令[[复合命令 。

I find the double-bracket version of test makes writing logic tests more natural:我发现test双括号版本使编写逻辑测试更自然:

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

Shorter form:较短的形式:

# if $DIR is a directory, then print yes
[ -d "$DIR" ] && echo "Yes"
  1. A simple script to test if a directory or file is present or not:一个简单的脚本来测试目录或文件是否存在:

     if [ -d /home/ram/dir ] # For file "if [ -f /home/rama/file ]" then echo "dir present" else echo "dir not present" fi
  2. A simple script to check whether the directory is present or not:一个简单的脚本来检查目录是否存在:

     mkdir tempdir # If you want to check file use touch instead of mkdir ret=$? if [ "$ret" == "0" ] then echo "dir present" else echo "dir not present" fi

    The above scripts will check if the directory is present or not上面的脚本将检查目录是否存在

    $? if the last command is a success it returns "0", else a non-zero value.如果最后一个命令成功,则返回“0”,否则返回非零值。 Suppose tempdir is already present.假设tempdir已经存在。 Then mkdir tempdir will give an error like below:然后mkdir tempdir将给出如下错误:

    mkdir: cannot create directory 'tempdir': File exists mkdir: 无法创建目录 'tempdir': 文件存在

To check if a directory exists you can use a 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 also do it in the 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

You can use test -d (see man test ).您可以使用test -d (参见man test )。

-d file True if file exists and is a directory. -d file如果文件存在并且是一个目录,则为真。

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.注意: test命令与条件表达式[ (参见: man [ )相同,因此它可以跨 shell 脚本移植。

[ - This is a synonym for the test builtin, but the last argument must, be a literal ] , to match the opening [ . [ - 这是test内置的同义词,但最后一个参数必须是文字] ,以匹配开头[

For possible options or further help, check:有关可能的选项或进一步的帮助,请检查:

  • help [
  • help test
  • man test or man [ man testman [
if [ -d "$DIRECTORY" ]; then  
    # Here if $DIRECTORY exists  
fi

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

[ -d . ] || echo "No"

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 standard error already. cd会给我一个标准的单行消息到标准错误 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.通过在子shell ( ... )中执行cd ,该命令不会影响调用者的当前目录。 If the directory exists, this subshell and the function are just a no-op.如果该目录存在,则此子shell 和函数只是一个空操作。

Next is the argument that we pass to cd : ${1:?pathname expected} .接下来是我们传递给cd的参数: ${1:?pathname expected} This is a more elaborate form of parameter substitution which is explained in more detail below.这是一种更复杂的参数替换形式,下面将更详细地解释。

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. Tl;dr:如果传递给此函数的字符串为空,我们将再次退出子 shell ( ... )并从函数返回并返回给定的错误消息。


Quoting from the ksh93 man page:引用ksh93手册页:

${parameter:?word}

If parameter is set and is non-null then substitute its value;如果parameter已设置且非空,则替换其值; otherwise, print word and exit from the shell (if not interactive).否则,打印word并从 shell 退出(如果不是交互式的)。 If word is omitted then a standard message is printed.如果word被省略,则打印一条标准消息。

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: parameter not set是不够的,所以我放大了我们在这里期望的值的类型 - 目录的pathname

A philosophical note:哲学笔记:

The shell is not an object oriented language, so the message says pathname , not directory . shell 不是面向对象的语言,所以消息说pathname ,而不是directory At this level, I'd rather keep it simple - the arguments to a function are just strings.在这个级别上,我宁愿保持简单——函数的参数只是字符串。

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

The above code checks if the directory exists and if it is writable.上面的代码检查目录是否存在以及是否可写。

DIRECTORY=/tmp

if [ -d "$DIRECTORY" ]; then
    echo "Exists"
fi

Try online在线尝试

More features using find使用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

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

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

There isn't any 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),因此好处大于麻烦。

Have you considered just doing whatever you want to do in the if rather than looking before you leap?你有没有考虑过在if中做任何你想做的事情,而不是在你跳跃之前先看?

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.如果您提供给pushd的路径存在,您将输入它并以0退出,这意味着语句的then部分将执行。 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).如果它不存在,则不会发生任何事情(除了一些输出说目录不存在,这对于调试来说可能是一个有用的副作用)。

It 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

The 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.同样的事情适用于cdmvrm等...如果您在不存在的文件上尝试它们,它们将退出并显示错误并打印一条消息说它不存在,然后您的then块将被跳过。 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.如果您在确实存在的文件上尝试它们,该命令将执行并以0状态退出,从而允许您的then块执行。

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

NB: Quoting variables is a good practice.注意:引用变量是一种很好的做法。

Explanation:解释:

  • -d : check if it's a directory -d :检查它是否是一个目录
  • -L : check if it's a symbolic link -L : 检查是否是符号链接

To check more than one directory use this code:要检查多个目录,请使用以下代码:

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

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

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

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

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

As per Jonathan 's 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
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 need to have the execute rights on the directory.如果要进入该目录,还需要对该目录具有执行权限。 Maybe you need to have write rights as well.也许您还需要具有写入权限。

Therefore:所以:

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

In kind of a ternary form,以一种三元形式,

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

And with test :并通过test

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

The ls command in conjunction with -l (long listing) option returns attributes information about files and directories. ls命令与-l (长列表)选项一起返回有关文件和目录的属性信息。
In particular the first character of ls -l output it is usually a d or a - (dash).特别是ls -l输出的第一个字符通常是d- (破折号)。 In case of a d the one listed is a directory for sure.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
file="foo" 
if [[ -e "$file" ]]; then echo "File Exists"; fi;

可以使用以下find

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

There are 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 standard output (not an elegant solution for my taste) and will have nonetheless a zero exit.唯一的问题是,如果搜索到的目录不存在,“查找”命令将不会在标准输出中打印任何内容(对我来说这不是一个优雅的解决方案)并且仍然会出现零退出。 Maybe someone could improve on this.也许有人可以改进这一点。

(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 an issue is found with one of the approaches provided above:如果使用上述方法之一发现问题:

With the ls command;使用ls命令; the cases when a directory does not exists - an error message is shown目录不存在的情况 - 显示错误消息

[[ `ls -ld SAMPLE_DIR| grep ^d | wc -l` -eq 1 ]] && echo exists || not exists

-ksh: not: not found [No such file or directory] -ksh: not: not found [没有这样的文件或目录]

Use the file program.使用file程序。 Considering all directories are also files in Linux, issuing the following command would suffice:考虑到 Linux 中的所有目录也是文件,发出以下命令就足够了:

file $directory_name

Checking a nonexistent file: file blah检查不存在的文件: file blah

Output: cannot open 'blah' (No such file or directory)输出: cannot open 'blah' (No such file or directory)

Checking an existing directory: file bluh检查现有目录: file bluh

Output: bluh: directory输出: bluh: directory

一个班轮:

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

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").说明:如果目录或符号链接不存在,“ls”命令会给出错误“ls: /x: No such file or directory”,并将返回码(您可以通过“$?”检索)设置为非-null(通常为“1”)。 Be sure that you check the return code directly after calling "ls".确保在调用“ls”后直接检查返回码。

From script file myScript.sh :从脚本文件myScript.sh

if [ -d /home/ec2-user/apache-tomcat-8.5.5/webapps/Gene\ Directory ]; then
   echo "Directory exists!"
   echo "Great"
fi

Or或者

if [ -d '/home/ec2-user/apache-tomcat-8.5.5/webapps/Gene Directory' ]; then
   echo "Directory exists!"
   echo "Great"
fi

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 a Dropbox symbolic path.其他解决方案都不适用于我的 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:"

You'll probably want to know how to successfully navigate to Dropbox from Bash as well.您可能还想知道如何从 Bash 成功导航到 Dropbox。 So here is the script in its entirety.所以这里是完整的脚本。

https://pastebin.com/QF2Exmpn https://pastebin.com/QF2Exmpn

Just as an alternative to the '[ -d ]' and '[ -h ]' options, you can make use of stat to obtain the file type and parse it.作为 '[ -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

Test data:测试数据:

$ 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

I collected below a few less-known options to check directory existence, also the well-known ones were included (some of them might be already covered in the previous answers).我在下面收集了一些鲜为人知的选项来检查目录是否存在,也包括了众所周知的选项(其中一些可能已经在之前的答案中介绍过)。

All examples were tested on Ubuntu 18.04 , so they might not always work on some other type of OS'es (most of them should work smoothly in most Linux distributions or on Mac OS though).所有示例都在Ubuntu 18.04上进行了测试,因此它们可能并不总是适用于某些其他类型的操作系统(尽管它们中的大多数应该在大多数Linux发行版或Mac OS上都能顺利运行)。 The directory path can be changed to any directoy, in the examples below /tmp was used.目录路径可以更改为任何目录,在下面的示例中使用了/tmp

  1. Using the test command:使用测试命令:
if test -d /tmp; then
  echo "Directory exists"
else
  echo "Directory does not exist"
fi

  1. Using the [ -d ] test operator:使用[ -d ]测试运算符:
if [ -d /tmp ]; then
  echo "Directory exists"
else
  echo "Directory does not exist"
fi
  1. Using the [[ -d ]] test operator (This is similar to the previous one, but more powerful):使用[[ -d ]]测试运算符(这与前一个类似,但更强大):
if [[ -d /tmp ]]; then
  echo "Directory exists"
else
  echo "Directory does not exist"
fi
  1. Using the -e test operator (This checks if file exist, it works for both file and directory):使用-e测试运算符(这检查文件是否存在,它适用于文件和目录):
if [ -e /tmp ]; then
  echo "Directory exists"
else
  echo "Directory does not exist"
fi
  1. Using the ls command and redirecting the output to /dev/null :使用ls命令并将 output 重定向到/dev/null
if ls -d /tmp > /dev/null 2>&1; then
  echo "Directory exists"
else
  echo "Directory does not exist"
fi
  1. Using find command:使用find命令:
if find /tmp -mindepth 1 -print -quit 2>/dev/null; then
  echo "Directory exists"
else
  echo "Directory does not exist"
fi
  1. Using stat command:使用stat命令:
if stat /tmp > /dev/null 2>&1; then
  echo "Directory exists"
else
  echo "Directory does not exist"
fi
  1. Using dirname command:使用dirname命令:
if [ "$(dirname /tmp)" != "/tmp" ]; then
  echo "Directory exists"
else
  echo "Directory does not exist"
fi
  1. Using readlink command:使用readlink命令:
if readlink -e /tmp > /dev/null 2>&1; then
  echo "Directory exists"
else
  echo "Directory does not exist"
fi
  1. Using realpath command:使用realpath命令:
if realpath /tmp > /dev/null 2>&1; then
  echo "Directory exists"
else
  echo "Directory does not exist"
fi
  1. Using cd command:使用cd命令:
if cd /tmp; then
  echo "Directory exists"
  cd - >/dev/null
else
  echo "Directory does not exist"
fi
  1. Using grep command:使用grep命令:
if ls -d /tmp 2>/dev/null | grep -q '/tmp'; then
  echo "Directory exists"
else
  echo "Directory does not exist"
fi
  1. Using Python os module:使用 Python os模块:
if python -c "import os; print(os.path.isdir('/tmp'))" | grep -q "True"; then
  echo "Directory exists"
else
  echo "Directory does not exist"
fi

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM