Maslow
Maslow

Reputation: 18746

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

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?

Upvotes: 9

Views: 19510

Answers (2)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200293

I'd probably rather do the check like this:

s1=DEV-0-1
s2=DEV

if [ "${s1:0:${#s2}}" == "$s2" ]; then
  echo "yes"
fi

Upvotes: 7

P.P
P.P

Reputation: 121397

You missed a space there:

 if [[ 'DEV-0-1' == DEV* ]]; then echo "yes"; fi
      ^^

Upvotes: 13

Related Questions