1

For some reason I need to run a perl script in Bash. But there is a counter in perl which I want to use back in the shell script (parent). But for some reason I am not able to fetch it.

Can somebody please help me with this? (The only alternative I am doing is writing the perl return code in a file and then reading the file in shell script (parent) to fetch the value).

#!/bin/sh
cnt=1
echo "In Bash (cnt: $cnt)"
perl - $cnt <<'EOF'
    #!/usr/bin/perl -w
    my $cnt=shift;
    while ($cnt<100) {
        $cnt++;
    }
    print "In Perl (cnt: $cnt)\n";
    exit $cnt;
EOF
echo "In Bash (cnt: $cnt)"

Output:

$ ./testPerl
In Bash (cnt: 1)
In Perl (cnt: 100)
In Bash (cnt: 1)

Ross
  • 1,313
  • 4
  • 16
  • 24
tranceporter
  • 189
  • 1
  • 15
  • 4
    You cannot share variables across totally different languages! Either emit a piece of shell script that sets the variable to the correct value when eval'd, or parse the Perl output in Bash! See also [this recent question](http://stackoverflow.com/q/17031237/1521179). – amon Jun 11 '13 at 13:11
  • But isnt it same as exiting perl with a return code. If we can pass shell variables in perl cant we get a return code. – tranceporter Jun 11 '13 at 13:13
  • 3
    The exit code is meant to indicate if a process succeeded or exited with an error. Your bash script never even looks at the exit code of the perl script. Use STDOUT to return data, like any other program. You'll find bash constructs like backticks or `$(command)` useful. – amon Jun 11 '13 at 13:16

3 Answers3

3
#!/bin/sh
cnt=1
echo "In Bash (cnt: $cnt)"
cnt=`perl -e '
    my $cnt=shift;
    while ($cnt<100) {
        $cnt++;
    }
    print $cnt;
    exit' $cnt`
echo "In Bash (cnt: $cnt)"
askovpen
  • 2,438
  • 22
  • 37
1

@askovpen answered this before me. I want to demonstrate that you can still use a heredoc if you want:

#!/bin/sh
cnt=1
echo "before (cnt: $cnt)"
cnt=$(
perl -l - $cnt <<'EOF'
    $x = shift;
    $x++ while $x < 100;
    print $x;
EOF
)
echo "after (cnt: $cnt)"

I changed perl's variable name to make it clear the variable isn't shared at all

glenn jackman
  • 238,783
  • 38
  • 220
  • 352
-1
#!/bin/sh
cnt=1
echo "In Bash (cnt: $cnt)"
perl - $cnt <<'EOF'
    #!/usr/bin/perl -w
    my $cnt=shift;
    while ($cnt<100) {
        $cnt++;
    }
    print "In Perl (cnt: $cnt)\n";
    exit $cnt;
EOF
cnt=$?;
echo "In Bash (cnt: $cnt)"
askovpen
  • 2,438
  • 22
  • 37
  • 1
    While this works, it is an incredibly bad idea. An exit code is an integer in the range from 0 to 255 (one byte). It is quite easy to make overflow errors. – amon Jun 11 '13 at 13:40
  • I think you are right amon. This is what is happening. The cnt is getting returned, but if the value of cnt is > 255, then it is wrapped, and restarted from 0. – tranceporter Jun 11 '13 at 14:01