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)

3
  • 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. Commented Jun 11, 2013 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. Commented Jun 11, 2013 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. Commented Jun 11, 2013 at 13:16

3 Answers 3

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)"
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

-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)"

2 Comments

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.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.