Passing the search string to grep as a shell variable

I need to write a small bash script that determines if a string is valid for bash variable naming rules. My script takes the variable name as an argument. I am trying to pass this argument to the grep command with my regular expression, but all I tried is grep trying to open the value passed as a file.

I tried placing it after the command as such grep "$regex" "$1" and also tried passing it as redirected input, both with and without quotes grep "$regex" <"$1" 

and both times grep tries to open it as a file. Is there a way to pass a variable to grep?

+4
source share
2 answers

Both examples interpret "$ 1" as the file name. To use a string, you can use

 echo "$1" | grep "$regex" 

or bash specific string "here"

 grep "$regex" <<< "$1" 

You can also do it faster without grep with

 [[ $1 =~ $regex ]] # regex syntax may not be the same as grep's 

or if you just check the substring,

 [[ $1 == *someword* ]] 
+7
source

You can use the built-in function bash =~ . Like this:

 if [[ "$string" =~ $regex ]] ; then echo "match" else echo "dont match" fi 
0
source

All Articles