3

In a bash-script I need to check if the string $HEADER 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.

Jahid
  • 21,542
  • 10
  • 90
  • 108
much
  • 47
  • 1
  • 1
  • 4

4 Answers4

10

This should work:

if [[ $HEADER = '/*'* ]]

Another solution would be:

if [ "${HEADER:0:2}" = '/*' ]

Or

if [[ "${HEADER:0:2}" = '/*' ]]
Jahid
  • 21,542
  • 10
  • 90
  • 108
4

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 = '/*'* ]]
Community
  • 1
  • 1
chepner
  • 497,756
  • 71
  • 530
  • 681
2

This should help

if [[ $(echo $HEADER | grep -E '^\/\*' | wc -l) -gt 0 ]]
GMichael
  • 2,726
  • 1
  • 20
  • 30
1

You already have a few solutions, but

[ "${HEADER#/\*}" != "${HEADER}" ]

works with POSIX shells without using external tools (not counting [) or bashisms.

Interestingly enough, this approach was missing from the marked duplicate.

dhke
  • 15,008
  • 2
  • 39
  • 56