“如果变量不包含”不起作用

“如果变量不包含”不起作用

这是我的脚本

if [[ ! $url == *.txt ]]
then
exit
fi

我也尝试过:

if [[ ! "$url" == *.txt ]]
then
exit
fi

和:

if [[ "$url" !== *.txt ]]
then
exit
fi

但即使$url包含*.txt它仍然exit是吗?

答案1

不等式的正确运算符是!=。见下文:

url=/heads/paths/lol.txt
if [[ $url != *.txt ]] ; then echo "does not contain txt"; else echo "contains txt"; fi

它给:

contains txt

参考:http://tldp.org/LDP/abs/html/comparison-ops.html

答案2

你应该做这个:

[ -n "${url%%*.txt}" ] && 
echo "\$url is not null and does not end with the string '.txt'"

相关内容