当我给脚本一个参数时,下面的shell脚本工作正常。 [./test dir_name]
但是,当我没有给出目录名时,脚本不会失败[即不属于错误消息]。在这种情况下脚本没有失败的原因是什么?
#!/bin/sh
echo "directory name is " $1
if [ ! -d $1 ];
then
echo "ERROR: directory doesn't exist"
fi
由于你没有引用$1
并且它的扩展是空字符串,所以在扩展经历分词后你的命令变成[ ! -d ]
。你正在测试字符串-d
是非空的,它是什么。
始终引用参数扩展;你会知道什么时候做的不对。
echo "directory name is $1"
if [ ! -d "$1" ]; then