How do I test if a string starts with another in bash?
Solution 1
You missed a space there:
if [[ 'DEV-0-1' == DEV* ]]; then echo "yes"; fi
^^
Solution 2
I'd probably rather do the check like this:
s1=DEV-0-1
s2=DEV
if [ "${s1:0:${#s2}}" == "$s2" ]; then
echo "yes"
fi
Nicolas Fall
F# happy/crazy fan of [Elmish;React;Knockout;Fable;Angular 1.0] in that order. Roslyn consumer since < June of 2012 Asp.net MVC lover since before 1.0 RTM
Updated on July 23, 2022Comments
-
Nicolas Fall almost 2 years
Very similar but not duplicate : https://stackoverflow.com/a/2172367/57883
I'm in Git Bash 3.1 (at least that's what comes up in the prompt when I type bash inside git bash.
and
$ test [["DEV-0" == D*]] || echo 'fail'
prints fail.if [['DEV-0-1' == DEV* ]]; then echo "yes";
says[[DEV-0-1: command not found
I'm trying to test ifgit branch
returns something that starts with DEV. but I can't seem to apply the answer. is it because all my attempts are using a string literal on the left instead of a variable value?I've also tried it on ideone http://ideone.com/3IyEND
and no luck. It's been ~14 years since I was good with a linux prompt.
What am I missing for a string starts with test in bash?
-
Gilles Quenot over 11 yearsSpeedy Gonzales is... Indian =)
-
P.P over 11 yearshehe.. I've hit this error enough times to see it right away ;-)
-
ormaaj over 11 years@Maslow pattern-matching is only supported by
[[
. If you want POSIX, you have to usecase..esac
or[ -z "${var##dev*}" ]
. -
P.P over 11 years@Maslow When you do
D*
it's going to be expanded by the shell before comparison.test [[ $a == D* ]] || echo 'test fail'
is not going to work. That's why you get that error. -
Nicolas Fall over 11 yearsso I kinda like the
test condition ||
syntax is there a way to use that test deal for a string starts with condition? -
P.P over 11 years@Maslow You can my example here: ideone.com/sC3bbm . The part
${a:0:1}
basically gets the substring ofa
starting from index 0 of length1
and it's compared. Same way you can get different length substrings with different lengths. E.g.${a:0:2}
will give the first 2 letters ina
.