什么命令检查Bash shell脚本中是否存在目录?
当前回答
实际上,您应该使用几种工具来获得防弹方法:
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),所以好处大于麻烦。
其他回答
DIRECTORY=/tmp
if [ -d "$DIRECTORY" ]; then
echo "Exists"
fi
联机尝试
在Bash脚本中引用变量时,始终将变量括在双引号中。
if [ -d "$DIRECTORY" ]; then
# Will enter here if $DIRECTORY exists, even if it contains spaces
fi
现在的孩子们在他们的目录名中添加空格和许多其他有趣的字符。(空间!在我的时代,我们没有花哨的空间!)有一天,这些孩子中的一个会运行你的脚本,$DIRECTORY设置为“My M0viez”,你的脚本就会崩溃。你不想这样。所以使用双引号。
要检查多个目录,请使用以下代码:
if [ -d "$DIRECTORY1" ] && [ -d "$DIRECTORY2" ] then
# Things to do
fi
Git Bash+Dropbox+Windows:
其他解决方案都不适用于我的Dropbox文件夹,这很奇怪,因为我可以Git推送到Dropbox符号路径。
#!/bin/bash
dbox="~/Dropbox/"
result=0
prv=$(pwd) && eval "cd $dbox" && result=1 && cd "$prv"
echo $result
read -p "Press Enter To Continue:"
您可能也想知道如何从Bash成功导航到Dropbox。这是整个脚本。
https://pastebin.com/QF2Exmpn
这个答案被包装成一个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";
推荐文章
- RVM不是一个函数,用' RVM use…’不会起作用
- 如何打破一个循环在Bash?
- 如何从终端机发送电子邮件?
- 如何将文件指针(file * fp)转换为文件描述符(int fd)?
- Linux Bash中双&和分号有什么区别?
- 如何合并2 JSON对象从2个文件使用jq?
- 在Bash中模拟do-while循环
- 在Bash中将输出赋给变量
- 如何在Mac OS X 10.6中使硬件发出哔哔声
- Node.js同步执行系统命令
- 从Docker容器获取环境变量
- 如何重定向标准derr和标准输出到不同的文件在同一行脚本?
- 如何循环通过一个目录递归删除具有某些扩展名的文件
- 在Bash中获取日期(比当前时间早一天)
- Linux: kill后台任务