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

Community
  • 1
  • 1
Ullan
  • 1,311
  • 8
  • 21
  • 34
  • Fwiw, `[[ $var == set\ @test_date\ =* ]]` works. I'm not sure enough of the ins and outs to explain the how & why. – Wrikken Jun 25 '14 at 18:45

2 Answers2

1

This should work:

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

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

anubhava
  • 761,203
  • 64
  • 569
  • 643
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

David C. Rankin
  • 81,885
  • 6
  • 58
  • 85