0

I have a Perl script that uses some local variables as per below:

my $cool_variable="Initial value";
COOLVAR="Initial value for COOLVAR"

I would like to replace the content between the quotes using a bash script.

I got it to work for a non-variable like below:

#!/bin/sh
dummy_var="Replaced value"
sed -i -r "s#^(COOLVAR=).*#\1$dummy_var#" perlscript.pl

But if I replace it with cool_variable or $cool_variable:

sed -i -r "s#^($cool_variable=).*#\1$dummy_var#" perlscript.pl

It does not work..

brian d foy
  • 129,424
  • 31
  • 207
  • 592
derwian36
  • 63
  • 5
  • 1
    Rather than editing the perl script, why not have it read the necessary value from a configuration file, which could be as simple as just a text file containing the desired text. Then the Perl script merely needs to read the contents of the file to initialize `COOLVAR`. – chepner Nov 03 '22 at 17:24
  • What is this supposed to be in your Perl code: `COOLVAR="Initial value for COOLVAR"`. If I try to run that code I get `Can't modify constant item in scalar assignment` compilation error. – TLP Nov 04 '22 at 08:58

1 Answers1

1

The are multiple code injection bugs in that snippet. You shouldn't be generating code from the shell or sed.


Say you have

var=COOLVAR
val=coolval

As per How can I process options using Perl in -n or -p mode?, you can use any of

perl -spe's{^$var=\K.*}{"\Q$val\E";};' -- -var="$var" -val="$val" perlscript.pl
var=var val=val perl -pe's{^$ENV{var}=\K.*}{"\Q$ENV{val}\E";};' perlscript.pl
export var
export val
perl -pe's{^$ENV{var}=\K.*}{"\Q$ENV{val}\E";};' perlscript.pl

to transform

COOLVAR="dummy";
HOTVAR="dummy";

into

COOLVAR="coolvar";
HOTVAR="dummy";

The values are passed to the program using arguments to avoid injecting them into the fixer, and the fixer uses Perl's quotemeta (aka \Q..\E) to quote special characters.

Note that $var is assumed to be a valid identifier. No validation checks are performed. This program is absolutely unsafe using untrusted input.

Use -i to modify the file in place.

ikegami
  • 367,544
  • 15
  • 269
  • 518