Bash条件变量与目录

时间:2016-11-15 01:29:58

标签: bash shell conditional

我对bash命令行中使用的条件语句的结构有疑问。

This question显示:

if [ -z "${VAR}" ]; then echo "VAR is unset or set to the empty string"

此处,只有在变量then 不存在时才会调用VAR。这是从here确认的。

但是,对于目录,this question显示:

if [ -d $directory_name ]; then echo "Directory already exists"

此处,只有在变量then 存在时才会调用directory_name。这是从here确认的(向下滚动到-d)。

我的问题: 我最近试图检查是否variable existed or not。当我尝试将相同的逻辑应用于目录时,我很惊讶它无法完成。这是我试过的:

dir_full_path='/mnt/iso'
if [ -d $dir_full_path ]; then echo 'Directory does not exist'; else echo 'Does exist'; fi

当我运行这两行时,目录路径/mnt/iso确实存在。所以我期望条件返回Directory does not exist。相反,它做了相反的事情,并返回Does exist

问题: 这很令人困惑,因为似乎条件的结构不能用于目录和变量。这是真的?如果是这样,那么这个差异是在某处记录的吗?

1 个答案:

答案 0 :(得分:2)

以下是正确使用这些命令,可以通过运行找到 帮助测试

if [ -z "$j" ]
then
  echo '$j is empty'
fi

if [ -n "$j" ]
then
  echo '$j is not empty'
fi

if [ -d /mnt/iso ]
then
  echo '/mnt/iso is a directory'
fi