什么命令检查Bash shell脚本中是否存在目录?
当前回答
在三元形式中,
[ -d "$directory" ] && echo "exist" || echo "not exist"
通过测试:
test -d "$directory" && echo "exist" || echo "not exist"
其他回答
可以使用以下发现,
find . -type d -name dirname -prune -print
这个答案被包装成一个shell脚本
示例
$ is_dir ~
YES
$ is_dir /tmp
YES
$ is_dir ~/bin
YES
$ mkdir '/tmp/test me'
$ is_dir '/tmp/test me'
YES
$ is_dir /asdf/asdf
NO
# Example of calling it in another script
DIR=~/mydata
if [ $(is_dir $DIR) == "NO" ]
then
echo "Folder doesnt exist: $DIR";
exit;
fi
is目录
function show_help()
{
IT=$(CAT <<EOF
usage: DIR
output: YES or NO, depending on whether or not the directory exists.
)
echo "$IT"
exit
}
if [ "$1" == "help" ]
then
show_help
fi
if [ -z "$1" ]
then
show_help
fi
DIR=$1
if [ -d $DIR ]; then
echo "YES";
exit;
fi
echo "NO";
使用文件程序。考虑到所有目录也是Linux中的文件,发出以下命令就足够了:
文件$directory_name
检查不存在的文件:文件blah
输出:无法打开“blah”(没有这样的文件或目录)
检查现有目录:文件bluh
输出:bluh:目录
您可以使用test-d(参见man test)。
-d file如果文件存在并且是目录,则为True。
例如:
test -d "/etc" && echo Exists || echo Does not exist
注意:测试命令与条件表达式[(参见:man[)相同,因此它可以跨shell脚本移植。
[-这是测试内置的同义词,但最后一个参数必须是文字],以匹配开头[。
有关可能的选项或进一步帮助,请检查:
帮助[帮助测试人工测试或人工[
要检查多个目录,请使用以下代码:
if [ -d "$DIRECTORY1" ] && [ -d "$DIRECTORY2" ] then
# Things to do
fi