Search code examples
shellshposix

How do I compare strings in Bourne Shell?


I need to compare strings in shell:

var1="mtu eth0"

if [ "$var1" == "mtu *" ]
then
    # do something
fi

But obviously the "*" doesn't work in Shell. Is there a way to do it?


Solution

  • bash

    Shortest fix:

    if [[ "$var1" = "mtu "* ]]
    

    Bash's [[ ]] doesn't get glob-expanded, unlike [ ] (which must, for historical reasons).


    bash --posix

    Oh, I posted too fast. Bourne shell, not Bash...

    if [ "${var1:0:4}" == "mtu " ]
    

    ${var1:0:4} means the first four characters of $var1.


    /bin/sh

    Ah, sorry. Bash's POSIX emulation doesn't go far enough; a true original Bourne shell doesn't have ${var1:0:4}. You'll need something like mstrobl's solution.

    if [ "$(echo "$var1" | cut -c0-4)" == "mtu " ]