Bash 条件结构 - 变量与目录
Structure of Bash conditional - variable versus directory
我对要在 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
)。
我的问题:
我最近试图检查是否 。当我尝试将相同的逻辑应用于目录时,我很惊讶它无法完成。这是我尝试过的:
dir_full_path='/mnt/iso'
if [ -d $dir_full_path ]; then echo 'Directory does not exist'; else echo 'Does exist'; fi
当我运行这两行时,目录路径/mnt/iso
确实不存在。所以我希望有条件的 return Directory does not exist
。相反,它做了相反的事情,它 returned Does exist
.
问题:
这非常令人困惑,因为它看起来像条件 cannot 的相同结构可用于目录和变量。这是真的?如果是这样,那么这种差异是否记录在某处?
下面是这些命令的正确使用方法,可以参考运行
帮助测试:
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
我对要在 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
)。
我的问题:
我最近试图检查是否
dir_full_path='/mnt/iso'
if [ -d $dir_full_path ]; then echo 'Directory does not exist'; else echo 'Does exist'; fi
当我运行这两行时,目录路径/mnt/iso
确实不存在。所以我希望有条件的 return Directory does not exist
。相反,它做了相反的事情,它 returned Does exist
.
问题: 这非常令人困惑,因为它看起来像条件 cannot 的相同结构可用于目录和变量。这是真的?如果是这样,那么这种差异是否记录在某处?
下面是这些命令的正确使用方法,可以参考运行 帮助测试:
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