什么命令检查Bash shell脚本中是否存在目录?
当前回答
要检查多个目录,请使用以下代码:
if [ -d "$DIRECTORY1" ] && [ -d "$DIRECTORY2" ] then
# Things to do
fi
其他回答
file="foo"
if [[ -e "$file" ]]; then echo "File Exists"; fi;
从脚本文件myScript.sh:
if [ -d /home/ec2-user/apache-tomcat-8.5.5/webapps/Gene\ Directory ]; then
echo "Directory exists!"
echo "Great"
fi
Or
if [ -d '/home/ec2-user/apache-tomcat-8.5.5/webapps/Gene Directory' ]; then
echo "Directory exists!"
echo "Great"
fi
实际上,您应该使用几种工具来获得防弹方法:
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 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块执行。
可以使用以下发现,
find . -type d -name dirname -prune -print