0
var1="temp-pprod-deployment"

Need a shell script for the below use case;

if the above variable $var1 value contains "prod" string then execute a print message eg. echo "Found" else echo "Not found"

  • Do you really need a regex for this? wouldn't a simple shell glob suffice e.g. (in a Bourne-like shell) case $var1 in *prod*) echo 'Found';; *) echo 'Not found';; esac – steeldriver Oct 25 '18 at 20:24
0

You can do something like this:

var1="temp-pprod-deployment"
if `echo "$var1" | grep -q "prod"` ;then
   echo "\$var1 contains word 'prod'"
else 
   echo "Not found."
fi

Explanation: You are getting output of variable and piping it to grep for regex. The -q option, means to return 0 on success(true) and 1 on failure(false), which is test-ed with if.

0

Use bashes / operator to remove the test string from the variable contents, and see if that operation has changed it. If it has, you know the string is present:

$ var1="temp-pprod-deployment"
$ var2="temp-pdev-deployment"
$ [ "${var1/prod}" == "$var1" ] && echo not found
$ [ "${var2/prod}" == "$var2" ] && echo not found
not found
$ [ "${var1/dev}" == "$var1" ] && echo not found
not found
$ [ "${var2/dev}" == "$var2" ] && echo not found

In full compliance with the OP:

if [ "${var1/prod}" != "${var1}" ]
then
  echo "Found."
else
  echo "Not found."
fi

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.