n-alexander n-alexander - 29 days ago 9
Bash Question

How do I compare strings in Bourne Shell?

I need to compare strings in shell:

var1="mtu eth0"

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

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

Answer Source


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.


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 " ]