什么命令检查Bash shell脚本中是否存在目录?
当前回答
要检查目录是否存在,可以使用简单的if结构,如下所示:
if [ -d directory/path to a directory ] ; then
# Things to do
else #if needed #also: elif [new condition]
# Things to do
fi
你也可以用否定的方式:
if [ ! -d directory/path to a directory ] ; then
# Things to do when not an existing directory
注意:小心。在开口大括号和闭合大括号的两侧留出空白。
使用相同的语法,您可以使用:
-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
其他回答
你有没有考虑过只做你想做的事,而不是三思而后行?
也就是说,如果您想在输入目录之前检查其是否存在,请尝试执行以下操作:
if pushd /path/you/want/to/enter; then
# Commands you want to run in this directory
popd
fi
如果您给pushd的路径存在,您将输入它,它将以0退出,这意味着将执行语句的then部分。如果它不存在,什么都不会发生(除了一些输出说目录不存在,这可能对调试有帮助的副作用)。
这似乎比这更好,这需要重复自己:
if [ -d /path/you/want/to/enter ]; then
pushd /path/you/want/to/enter
# Commands you want to run in this directory
popd
fi
同样的方法也适用于cd、mv、rm等……如果您在不存在的文件上尝试它们,它们将以错误退出并打印一条消息表示不存在,然后将跳过您的then块。如果您在确实存在的文件上尝试它们,则命令将执行并退出,状态为0,从而允许您的then块执行。
测试目录或文件是否存在的简单脚本:if[-d/home/ram/dir]#对于文件“if[-f/home/rama/file]”然后echo“目录存在”其他的echo“目录不存在”传真检查目录是否存在的简单脚本:mkdir tempdir#如果要检查文件,请使用touch而不是mkdirret=$?如果[“$ret”==“0”]然后echo“目录存在”其他的echo“目录不存在”传真以上脚本将检查目录是否存在$? 如果最后一个命令成功,则返回“0”,否则返回非零值。假设tempdir已经存在。然后mkdir tempdir将给出如下错误:mkdir:无法创建目录“tempdir”:文件存在
根据Jonathan的评论:
如果您想创建目录,但它还不存在,那么最简单的方法是使用mkdir-p创建目录-以及路径上的任何缺失目录-如果目录已经存在,则不会失败,因此您可以使用以下方法一次性完成:
mkdir -p /some/directory/you/want/to/exist || exit 1
作为“[-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
测试数据:
$ 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
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