检查外壳脚本中是否存在目录
时间:2020-03-05 18:52:30 来源:igfitidea点击:
什么命令可用于检查Shell脚本中的目录是否存在?
解决方案
回答
要检查shell脚本中是否存在目录,可以使用以下命令:
if [ -d "$DIRECTORY" ]; then # Control will enter here if $DIRECTORY exists. fi
或者检查目录是否不存在:
if [ ! -d "$DIRECTORY" ]; then # Control will enter here if $DIRECTORY doesn't exist. fi
但是,正如乔恩·埃里克森(Jon Ericson)所指出的,如果我们不考虑到目录的符号链接也会通过此检查,则后续命令可能无法按预期运行。
例如。运行这个:
ln -s "$ACTUAL_DIR" "$SYMLINK" if [ -d "$SYMLINK" ]; then rmdir "$SYMLINK" fi
会产生错误信息:
rmdir: failed to remove `symlink': Not a directory
因此,如果后续命令需要目录,则可能必须区别对待符号链接:
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
请特别注意用于包装变量的双引号,其原因由8jean在另一个答案中解释。
如果变量包含空格或者其他异常字符,则可能会导致脚本失败。
回答
使用`查找更多功能
- 检查文件夹在子目录中是否存在:
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
- 根据当前目录中的模式检查一个或者多个文件夹的存在:
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
- 两种组合。在以下示例中,它将检查当前目录中是否存在该文件夹:
found=`find -maxdepth 1 -type d -name "myDirectory"` if [ -n "$found"] then # The variable 'found' is not empty => "myDirectory"` exists. fi
回答
注意-d测试可以产生一些令人惊讶的结果:
$ ln -s tmp/ t $ if [ -d t ]; then rmdir t; fi rmdir: directory "t": Path component not a directory
文件位于:"目录何时不是目录?"答案:"当它是目录的符号链接时。"稍微更彻底的测试:
if [ -d t ]; then if [ -L t ]; then rm t else rmdir t fi fi
我们可以在Bash手册中找到有关Bash条件表达式以及[
内置命令和[[
复合命令"的详细信息。
回答
缩写形式:
[ -d "$DIR" ] && echo "Yes"
回答
我发现test
的双括号版本使编写逻辑测试更加自然:
if [[ -d "${DIRECTORY}" && ! -L "${DIRECTORY}" ]] ; then echo "It's a bona-fide directory" fi
回答
记住在引用变量时总是将变量用双引号引起来
bash脚本。这些天,孩子们长大了,他们的目录名称中可以有空格和许多其他有趣的字符。 (空格!回到我的时代,我们没有多余的空格!;))
有一天,其中一个孩子会在$ DIRECTORY设置为" My M0viez"的情况下运行脚本,并且脚本会崩溃。你不要那样所以用这个。
if [ -d "$DIRECTORY" ]; then # Will enter here if $DIRECTORY exists, even if it contains spaces fi
回答
或者完全没有用的东西:
[ -d . ] || echo "No"
回答
实际上,我们应该使用几种工具来获得防弹方法:
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
只要使用" $ {}"
,就不必担心空格和特殊字符。
请注意,的可移植性不如[]
,但由于大多数人都使用现代版本的Bash(毕竟,大多数人甚至不使用命令行:-p),所以这样做的好处大于麻烦。
回答
if [ -d "$DIRECTORY" ]; then # Will enter here if $DIRECTORY exists fi
这不是完全正确的...
如果要转到该目录,则还需要对该目录具有执行权限。也许我们还需要具有写权限。
因此:
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
回答
if [ -d "$Directory" -a -w "$Directory" ] then #Statements fi
上面的代码检查目录是否存在以及是否可写。