setting variable value to dynamic sed match - escaping hell

Hello All,

I'm trying to write a script that will perform a dynamic match (of a dynamic variable) and set a variable to have the resulting (match) value.

The idea is that the environment variable to check ($1) and the regular expression to use ($2) are given as parameters.

For example, to print the user's username only if it begins with an 'a', we would make the call:

check-var.sh USER "^a.*$"

I've tried doing this:

VAR_NAME=$1
 
VAR_REGEXP=$2
 
VAR_MATCH=`eval "echo \$${VAR_NAME} | sed -n \"/$VAR_REGEXP/p\""
 
echo $VAR_MATCH

But there seems to be a problem with by quoting and escaping because if I execute the eval directly like this:

eval "echo \$${VAR_NAME} | sed -n \"/$VAR_REGEXP/p\""

the expected result is printed.

Anyone out there have an idea of how I can capture the result in the VAR_MATCH variable? I ask because I actually need to work with the matched value later on in the script and not simply send it to stdout.

Thanks,

  • Andy

If you start the script with:

check-var.sh USER "^a.*$"

you can get the result in your script with:

VAR_MATCH=$(echo $1 | grep $2)

echo $VAR_MATCH

Or am I missing something?

1 Like

Looks like you missed the closing "`".

Further to majormark.

We need more backslash characters to properly escape the eval statement when run from within a shell script.
Also I had to export $USER before invoking the script.

VAR_MATCH=`eval "echo \\$\${VAR_NAME} | sed -n \"/${VAR_REGEXP}/p\""`

Thanks for quick answer; you put me on the right track.

What I am actually trying to do to check the *value* for the variable named in $1 and not the variable name itself.

What did the trick was:

VAR_MATCH=$(eval echo \$${VAR_NAME} | grep -e "$VAR_REGEXP")

Thanks for your help,

  • Andy

Just for interest, we can do this without "eval".

VAR_MATCH=$(set | grep \^"${VAR_NAME}=${VAR_REGEXP}")

We must not have a "^" at the start of $2 for this to work.