什么命令检查Bash shell脚本中是否存在目录?
当前回答
file="foo"
if [[ -e "$file" ]]; then echo "File Exists"; fi;
其他回答
使用-e检查将检查文件,其中包括目录。
if [ -e ${FILE_PATH_AND_NAME} ]
then
echo "The file or directory exists."
fi
在Bash脚本中引用变量时,始终将变量括在双引号中。
if [ -d "$DIRECTORY" ]; then
# Will enter here if $DIRECTORY exists, even if it contains spaces
fi
现在的孩子们在他们的目录名中添加空格和许多其他有趣的字符。(空间!在我的时代,我们没有花哨的空间!)有一天,这些孩子中的一个会运行你的脚本,$DIRECTORY设置为“My M0viez”,你的脚本就会崩溃。你不想这样。所以使用双引号。
作为“[-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
[ -d ~/Desktop/TEMPORAL/ ] && echo "DIRECTORY EXISTS" || echo "DIRECTORY DOES NOT EXIST"
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