1

I am trying to check if a string begins with a particular string. But the below code is not working.

// set @test_date = '123456'

if [[ $var == "set @test_date =*"  ]]; then
      echo "true"
else
    echo "false"
fi

I found the similar question here, but it not working for me

Thanks

1
  • Fwiw, [[ $var == set\ @test_date\ =* ]] works. I'm not sure enough of the ins and outs to explain the how & why. Commented Jun 25, 2014 at 18:45

2 Answers 2

1

This should work:

 [[ "$var" == "set @test_date ="*  ]] && echo "true" || echo "false"

* needs to be out of quotes for shell to expand.

Sign up to request clarification or add additional context in comments.

Comments

0

If you know what you are looking for, the following is generally the most robust:

[[ "${var:0:len_of_sub}" == "$substring" ]] && echo "${var:0:len_of_sub} matches $substring"

Further, you can adjust the beginning index 0 here, to start the match at any location. There are a number of way to do this, so you should consider all the answers. Another favorite (only works with the compound command [[ is:

[[ "$var" =~  "$substring" ]]

That will match substring anywhere within $var

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.