什么命令检查Bash shell脚本中是否存在目录?
当前回答
检查目录是否存在,否则创建一个:
[ -d "$DIRECTORY" ] || mkdir $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
一个衬垫:
[[ -d $Directory ]] && echo true
DIRECTORY=/tmp
if [ -d "$DIRECTORY" ]; then
echo "Exists"
fi
联机尝试
这个答案被包装成一个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:目录