在bash中检查目录是否存在失败

问题描述 投票:1回答:1

当我给脚本一个参数时,下面的shell脚本工作正常。 [./test dir_name]

但是,当我没有给出目录名时,脚本不会失败[即不属于错误消息]。在这种情况下脚本没有失败的原因是什么?

#!/bin/sh
echo "directory name is " $1
if [ ! -d $1 ];  
then
  echo "ERROR: directory doesn't exist"
fi
linux bash shell sh
1个回答
3
投票

由于你没有引用$1并且它的扩展是空字符串,所以在扩展经历分词后你的命令变成[ ! -d ]。你正在测试字符串-d是非空的,它是什么。

始终引用参数扩展;你会知道什么时候做的不对。

echo "directory name is $1"

if [ ! -d "$1" ]; then
© www.soinside.com 2019 - 2024. All rights reserved.