"If variable does not contain" not working

14,662

Solution 1

The correct operator for inequality is !=. See below:

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

It gives:

contains txt

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

Solution 2

You should do this:

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

Related videos on Youtube

DisplayName
Author by

DisplayName

Updated on September 18, 2022

Comments

  • DisplayName
    DisplayName almost 2 years

    This is my script

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

    I have also tried:

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

    and:

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

    But even though $url does contain *.txt it still exits?

    • Ketan Maheshwari
      Ketan Maheshwari over 9 years
      What is the exact value of $url?
    • DisplayName
      DisplayName over 9 years
      Its different every time but something like /heads/paths/lol.txt.
    • Stéphane Chazelas
      Stéphane Chazelas over 9 years
      What's the output of LC_ALL=C printf "%q\n" "$url"? Does running your script with bash -x confirm that it is exiting at that point?