Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute perl file from shell script

Tags:

shell

perl

I have a question about how to execute the perl file inside of a shell script

I have 2 files now, "test.sh" and "test.pl", here are example of my scripts

SHELL script

#!/bin/bash
perl FILEPATH/test.pl
......

PERL script

#!/usr/bin/perl
my $a = "hello"
sub saysomething
{
    print $a;
}
.....

The way I call the shell script is : under the path of shell scripts, execute "./test.sh"

All mentioned above are working under the environment GUN bash, version 4.2.24(1)-release (i686-pc-linux-gnu) + perl (v5.14.2)

But if I put those scripts on server (which I couldn't change the bash / perl version) GNU bash, version 4.2.10(1)-release (x86_64-pc-linux-gnu) + perl (v5.12.4), I got the followign message:

FILEPATH/test.pl: line 2: my: command not found

Does anybody know how can I solve this problem?

BTW, if I execute the perl script individually (perl FILEPATH/FILENAME.pl), it works perfectly.

like image 933
user1672190 Avatar asked Apr 15 '13 22:04

user1672190


2 Answers

In order to execute a perl script by .sh script you dont need to use perl prefix, but only:

#!/bin/sh

/somewhere/perlScript.pl

It will work without problem.

like image 190
Massimo Avatar answered Nov 15 '22 16:11

Massimo


This problem is at least two-fold. One, you have to have the location of Perl in your environment PATH. Two, the location of Perl may be different on different machines. One solution to both problems that I, and others, have used for years is to make use of a "magic header" of some sort at the top of Perl programs. The header identifies itself as a sh shell script and leverages the fact that /bin/sh exists in every version/flavor of Linux/UNIX. The header's job is to fortify the PATH with various possible Perl locations and then run the Perl script in place of itself (via exec). Here is a "Hello World" example:

1  #! /bin/sh --
2  eval '(exit $?0)' && eval 'PERL_BADLANG=x;PATH="/usr/bin:/bin:/usr/local/bin:$PATH";export PERL_BADLANG;: \
3  ;exec perl -x -S -- "$0" ${1+"$@"};#'if 0;
4  exec 'setenv PERL_BADLANG x;exec perl -x -S -- "$0" $argv:q;#'.q
5  #!/bin/perl -w
6  +($0=~/(.*)/s);do(index($1,"/")<0?"./$1":$1);die$@if$@;__END__+if 0;
7  # Above is magic header ... real Perl code begins here
8  use strict;
9  use warnings;
10 print "hello world!\n";

Note: I added line numbers just to make it clear where lines start and end.

like image 33
Ken Schumack Avatar answered Nov 15 '22 15:11

Ken Schumack