shell variable in a grep regex

BashGrep

Bash Problem Overview


I'm trying to use a variable in a grep regex. I'll just post an example of the failure and maybe someone can suggest how to make the variable be evaluated while running the grep command. I've tried ${var} as well.

$ string="test this"
$ var="test"
$ echo $string | grep '^$var'
$ 

Since my regex should match lines which start with "test", it should print the line echoed thru it.

$ echo $string
test this
$

Bash Solutions


Solution 1 - Bash

You need to use double quotes. Single quotes prevent the shell variable from being interpolated by the shell. You use single quotes to prevent the shell from doing interpolation which you may have to do if your regular expression used $ as part of the pattern. You can also use a backslash to quote a $ if you're using double quotes.

Also, you may need to put your variable in curly braces ${var} in order to help separate it from the rest of the pattern.

Example:

$ string="test this"
$ var="test"
$ echo $string | grep "^${var}"

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionmike_bView Question on Stackoverflow
Solution 1 - BashDavid W.View Answer on Stackoverflow