T.J.
T.J.

Reputation: 11

How to evaluate text strings provided by sed/grep/whatever?

This is for UNIX shell programming. It have to be supported by multiple UNIX platforms including Solaris, Linux, and AIX.

I have this scenario -- I am to read from a text file a string that may or may not contain an environment variable that may or may not be defined. For example:

<foo.bar> This error code was found: $(error_code)

I have the following code:

statement=$(sed -n $1'p' $messagefile)
echo $echo_flag $statement

$1 = line number supplied to this particular function/script.
$messagefile = filename of log file.
$echo_flag = "-e" in Linux, otherwise, empty.
$(error_code) = 42.

Instead of getting this when running:

<foo.bar> This error code was found: 42

I still get this:

<foo.bar> This error code was found: $(error_code)

How exactly do I tell the shell script that the value of statement should be evaluated further beyond what sed have done?

Upvotes: 0

Views: 406

Answers (2)

PhilR
PhilR

Reputation: 5602

It's unfortunate that the input text uses $(error_code) as the syntax, because that looks like process substitution to the shell. "eval" is closer to what you want, bu it's also a security risk to take user-controlled input and execute it directly.

This error code was found: rm -rf /

What you'd need to do is parse the input line for the expected syntax and process the "error_code" token by itself, test for an in-scope shellvar, print modified output etc.

Upvotes: 1

Steve Emmerson
Steve Emmerson

Reputation: 7832

I'm not certain that I understand what you're asking, but would changing the echo command to eval echo $echo_flag $statement do what you want?

Upvotes: 0

Related Questions