Skip to content

Propagating Perl exit code

October 3, 2012

I have a Perl script which calls another Perl script. The ‘child’ script returns the exit code of a system command and the ‘parent’ script should check it and act accordingly.

parent.pl:

my $result = system("perl child.pl");
print STDERR "Child script failed!\n" if ($result != 0);

child.pl:

my $exit_value = system($command);
exit($exit_value);

However, even if the system command fails, the parent script always receives “success”.

I finally discovered that Perl only considers the lower 8 bits of the exit() argument. Hence exit codes like 256 or 512 (which are quite common in operating system commands) are interpreted as 0.

I have two solutions for this problem:

1. If you need the exact exit code, Shift-right the exit code of the system command, then return the result.

my $result = system($command);
my $exit_value = $result >> 8;
exit($exit_value);

2. if you just need to know if the child command was successful, you can use “die” instead of “exit” in case the system command fails.

my $result = system($command);
die if ($result != 0);
Advertisements
Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: