much much - 2 years ago 290
Bash Question

bash: check if string starts with "/*"

In a bash-script I need to check if the string

starts with the character sequence "/*". I was trying:

if [ $(echo $HEADER | cut -c 1-2) = '/*' ]

It's not working as expected. It seems that the string is compared to the file list of the root directory.

How can I protect the characters / and * to be interpreted from the shell?

To protect the characters with a backslash isn't working either.

Answer Source

The problem is that the result of the command substitution is subject to file name generation. You need to quote that, as well as the expansion of $HEADER in the command substitution.

if [ "$(echo "$HEADER" | cut -c 1-2)" = '/*' ]

Since you are using bash, using the [[ command (which can perform pattern matching) is a superior solution though, as Jahid has already answered.

if [[ $HEADER = '/*'* ]]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download