Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

passing search string to grep as a shell variable

Tags:

grep

bash

I have to write a small bash script that determines if a string is valid for the bash variable naming rules. My script accepts the variable name as an argument. I am trying to pass that argument to the grep command with my regex but everything I tried, grep tries 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 the grep command?

like image 480
user1222073 Avatar asked Feb 17 '23 13:02

user1222073


1 Answers

Both your examples interpret "$1" as a filename. To use a string, you can use

echo "$1" | grep "$regex" 

or a bash specific "here string"

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're just checking for a substring,

[[ $1 == *someword* ]]
like image 98
that other guy Avatar answered Feb 20 '23 03:02

that other guy