0

I want to write a bash script that takes an input string and if it doesn't contain a particular tag in the beginning, add the tag to the beginning. The following is the script I wrote

#! /bin/bash

message=$1

tag="hello"

filter="^$tag.*"

if [[ ! $message =~ $filter ]]; then
   message="$tag $message"
fi

echo $message

This works well as long as the tag doesn't contain a regular expression specific keyword.

For example if the tag was set to [hello] the filter doesn't work since the square bracket is a keyword.

How to change the filter so that it ignores any keywords containing in the tag?

1
  • How are you running the script? Commented Feb 2, 2017 at 6:30

1 Answer 1

1

You can use shell patterns instead of regular expressions and quote them to avoid interpretation of meta characters:

if [[ $message != "$tag"* ]]; then
    message="$tag $message"
fi
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.