Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

bash

git-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?

like image 908
Maslow Avatar asked Mar 14 '13 19:03

Maslow


People also ask

How do you check a string starts with in bash?

Checking the string starts with another We can use the double equals ( == ) comparison operator in bash, to check if a string starts with another substring. In the above code, if a $name variable starts with ru then the output is “true” otherwise it returns “false”.

How do you check if a string is a substring of another in bash?

To check if a string contains a substring in Bash, use comparison operator == with the substring surrounded by * wildcards.

How do I compare two string variables in bash?

When comparing strings in Bash you can use the following operators: string1 = string2 and string1 == string2 - The equality operator returns true if the operands are equal. Use the = operator with the test [ command. Use the == operator with the [[ command for pattern matching.

How do you check if a string is present in another string in shell script?

The grep command can also be used to find strings in another string. In the following example, we are passing the string $STR as an input to grep and checking if the string $SUB is found within the input string. The command will return true or false as appropriate.


2 Answers

You missed a space there:

 if [[ 'DEV-0-1' == DEV* ]]; then echo "yes"; fi
      ^^
like image 121
P.P Avatar answered Oct 10 '22 23:10

P.P


I'd probably rather do the check like this:

s1=DEV-0-1
s2=DEV

if [ "${s1:0:${#s2}}" == "$s2" ]; then
  echo "yes"
fi
like image 44
Ansgar Wiechers Avatar answered Oct 10 '22 22:10

Ansgar Wiechers