Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pass on my Bash loop variable to the Perl interpreter?

Tags:

bash

perl

I'm trying to modify some scripts with a combination of Bash and Perl. The trouble is that Perl thinks that $index is its own variable, which is never defined:

for index in {1..25}; do
    perl -pi -e 's/\d+/$index/' cmd_$index.sh;
done

Is there a way to make $index wear its Bash cloak within the Perl one-liner?

like image 752
Zaid Avatar asked Jan 23 '12 15:01

Zaid


2 Answers

Squeeze an export index; in the do loop. Refer to $ENV{index} in the body of the Perl program.

Alternatively: Use the double quotes "… $index … " to interpolate the shell variable into the expression that makes up the body of the Perl program. In case you want to expand this one-liner, take care to properly escape Perl expressions, such as $ on variable names, and perhaps backslashes, so that are interpreted by Perl, not the shell.

like image 85
daxim Avatar answered Sep 28 '22 03:09

daxim


Use " instead of '. The bash can then substitute the variable before perl sees it.

like image 32
dgw Avatar answered Sep 28 '22 05:09

dgw