什么命令检查Bash shell脚本中是否存在目录?
当前回答
可以使用以下发现,
find . -type d -name dirname -prune -print
其他回答
[ -d ~/Desktop/TEMPORAL/ ] && echo "DIRECTORY EXISTS" || echo "DIRECTORY DOES NOT EXIST"
如果要检查目录是否存在,无论它是真实目录还是符号链接,请使用以下命令:
ls $DIR
if [ $? != 0 ]; then
echo "Directory $DIR already exists!"
exit 1;
fi
echo "Directory $DIR does not exist..."
解释:如果目录或符号链接不存在,则“ls”命令会给出错误“ls:/x:No such file or directory”,并将返回代码设置为非空(通常为“1”),您可以通过“$?”检索该代码。请确保在调用“ls”后直接检查返回代码。
更多功能使用查找
检查子目录中是否存在文件夹:find=`find-type d-name“myDirectory”`如果[-n“$found”]然后#变量“find”包含“myDirectory”所在的完整路径。#如果有多个名为“myDirectory”的文件夹,它可能包含多行。传真根据当前目录中的模式检查是否存在一个或多个文件夹:found=`find-maxdepth 1-type d-name“my*”`如果[-n“$found”]然后#变量“find”包含找到文件夹“my*”的完整路径。传真两种组合。在以下示例中,它检查当前目录中是否存在文件夹:find=`find-maxdeph 1-type d-name“myDirectory”`如果[-n“$found”]然后#变量'found'不为空=>“myDirectory”`存在。传真
ls命令与-l(长列表)选项一起返回有关文件和目录的属性信息。特别是ls-l输出的第一个字符通常是d或a-(破折号)。在d的情况下,列出的是一个目录。
仅一行中的以下命令将告诉您给定的ISDIR变量是否包含指向目录的路径:
[[ $(ls -ld "$ISDIR" | cut -c1) == 'd' ]] &&
echo "YES, $ISDIR is a directory." ||
echo "Sorry, $ISDIR is not a directory"
实际用途:
[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
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