How do I test if a string starts with another in bash?

19,040

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
Share:
19,040
Nicolas Fall
Author by

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, 2022

Comments

  • Nicolas Fall
    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 if git 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
    Gilles Quenot over 11 years
    Speedy Gonzales is... Indian =)
  • P.P
    P.P over 11 years
    hehe.. I've hit this error enough times to see it right away ;-)
  • ormaaj
    ormaaj over 11 years
    @Maslow pattern-matching is only supported by [[. If you want POSIX, you have to use case..esac or [ -z "${var##dev*}" ].
  • P.P
    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
    Nicolas Fall over 11 years
    so I kinda like the test condition || syntax is there a way to use that test deal for a string starts with condition?
  • P.P
    P.P over 11 years
    @Maslow You can my example here: ideone.com/sC3bbm . The part ${a:0:1} basically gets the substring of a starting from index 0 of length 1 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 in a.