检查Linux或Unix Shell中是否存在目录
时间:2020-01-09 10:37:38 来源:igfitidea点击:
如何检查在Linux或类似Unix的系统上运行的Shell脚本中是否存在目录?
如何检查Shell脚本中是否存在目录?
目录不过是用于以分层格式在Linux系统上存储文件的位置。
例如,$HOME/Downloads /将存储所有下载的文件,/tmp /将存储临时文件。
本教程将学习如何查看Linux或Unix-like系统中是否存在目录。
如何检查Linux中是否存在目录
- 可以使用以下语法检查Linux Shell脚本中是否存在目录:
[ -d "/path/dir/" ] && echo "Directory /path/dir/ exists." - 您可以使用
!来检查Unix上是否不存在目录:[ ! -d "/dir1/" ] && echo "Directory /dir1/ DOES NOT exists."
可以如下检查Linux脚本中是否存在目录:
DIR="/etc/httpd/"
if [ -d "$DIR" ]; then
# Take action if $DIR exists. #
echo "Installing config files in ${DIR}..."
fi
或者
DIR="/etc/httpd/"
if [ -d "$DIR" ]; then
### Take action if $DIR exists ###
echo "Installing config files in ${DIR}..."
else
### Control will jump here if $DIR does NOT exists ###
echo "Error: ${DIR} not found. Can not continue."
exit 1
fi
Linux检查目录是否存在并进行处理
这是一个示例shell脚本,用于查看Linux中是否存在文件夹:
#!/bin/bash
d=""
[ "$d" == "" ] && { echo "Usage: ./test.sh
./test.sh /tmp/
./test.sh /theitroad
directory"; exit 1; }
[ -d "${d}" ] && echo "Directory $d found." || echo "Directory $d not found."
如下运行:
#!/bin/bash
dldir="$HOME/linux/5.x"
_out="/tmp/out.$$"
# Build urls
url="some_url/file.tar.gz"
file="${url##*/}"
### Check for dir, if not found create it using the mkdir ##
[ ! -d "$dldir" ] && mkdir -p "$dldir"
# Now download it
wget -qc "$url" -O "${dldir}/${file}"
# Do something else below #
bash中检查是否存在目录,如果不存在则创建目录
这是一个示例shell脚本,用于检查目录是否不存在并根据我们的需要创建该目录:
DIR="foo" [ -d "$DIR" ] && echo "Found" ## ## this will fail as DIR will only expand to "foo" and not to "foo bar stuff" ## hence wrap it ## DIR="foo bar stuff" [ -d $DIR ] && echo "Found"
确保始终将shell变量(例如$DIR)括在双引号(" $DIR"中)以避免在shell脚本中出现任何意外情况:
test -d "DIRECTORY" && echo "Found/Exists" || echo "Does not exist"
使用test命令
可以使用test命令检查文件类型并比较值。
例如,查看FILE是否存在并且是目录。
语法为:
[ -d "DIR" ] && echo "yes" || echo "noop"
测试命令与[条件表达式相同。
因此,您也可以使用以下语法:

