Bash:如何检查目录是否存在?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/51342679/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 16:58:46  来源:igfitidea点击:

Bash: how to check if directory exists?

bashshell

提问by meallhour

I have written following if-else statementto check if directory1or directory2exists or not

我已经写了下面的if-else statement检查directory1directory2存在与否

if [ -d /opt/directory1 ] || [ -d /opt/directory2 ]; then
 echo "SUCCESS"
else
 echo "FAil
fi

However, on some servers I am getting an error

但是,在某些服务器上,我收到错误消息

[: /opt/directory1: binary operator expected

All servers are using bash

所有服务器都在使用 bash

回答by Ronan Boiteau

Using Bash, this will give you the behavior you're looking for:

使用 Bash,这将为您提供您正在寻找的行为:

if [[ -d /opt/directory1 ]] || [[ -d /opt/directory2 ]] ; then
    echo "SUCCESS"
else
    echo "FAIL"
fi

Note the usage of -don both conditions.

注意-d在这两种情况下的用法。

回答by Ronan Boiteau

Simple Shell script give you an answer.

简单的Shell脚本给你答案。

#!/bin/bash
DIR=""

if [ $# -ne 1 ]
then
    echo "Usage: ##代码## {dir-name}"
    exit 1
fi

if [ -d "$DIR" ]
then
    echo "$DIR directory  exists!"
else
    echo "$DIR directory not found!"
fi