Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I compare strings in Bourne Shell?

Tags:

shell

posix

sh

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?

like image 561
n-alexander Avatar asked Oct 08 '08 16:10

n-alexander


People also ask

How do you compare 2 strings?

Using String. equals() :In Java, string equals() method compares the two given strings based on the data/content of the string. If all the contents of both the strings are same then it returns true. If any character does not match, then it returns false.

How do you know if two strings are equal in Shell?

Details. Use == operator with bash if statement to check if two strings are equal. You can also use != to check if two string are not equal.


2 Answers

Use the Unix tools. The program cut will happily shorten a string.

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

... should do what you want.

like image 156
mstrobl Avatar answered Sep 22 '22 11:09

mstrobl


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 " ]
like image 26
ephemient Avatar answered Sep 18 '22 11:09

ephemient