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?
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.
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.
Use the Unix tools. The program cut
will happily shorten a string.
if [ "$(echo $var1 | cut -c 4)" = "mtu " ];
... should do what you want.
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 " ]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With