Home > Blockchain >  Require exit status !=0 for the main script if script within the system command/backtick fails
Require exit status !=0 for the main script if script within the system command/backtick fails

Time:10-08

Code of inter.pl is:

use strict;
use warnings;

my $var1=`cat /gra/def/ment/ckfile.txt`;  #ckfile.txt doesn't exist
print "Hello World";
exit 0;

When I execute inter.pl ( perl inter.pl), and check the exit status, I see it as 0. I know the reason why it comes out as 0 because it is a backtick that is executing it in a child xterm and then returning back after execution. So, exit status not equal to 0 would be seen in the child xterm.

But, what I want is that when anything goes wrong anywhere in the script, either within the script executing inside system command or backtick or in the main script, it should exit there and then with exit status not equal to 0.

Like here, as ckfile.txt isn't present, so ` cat /gra/def/ment/ckfile.txt` would give some error. Now, as it is an erroneous command in the script, the script should exit with status != 0. (Currently, it is exiting with status == 0.)

How can it be implemented?

CodePudding user response:

You can create a variable to store the status of your external command, then pass it to exit. The $? error variable holds the status of the backticks command.

use strict;
use warnings;

my $stat = 0;
my $var1=`cat /gra/def/ment/ckfile.txt`;  #ckfile.txt doesn't exist
$stat = 1 if $?;
print "Hello World\n";
exit $stat;

You set the $stat variable to 0 at the start of your code. If your code has multiple commands to run, you check the exit status after each command, and if it is non-zero, you simply keep setting $stat to 1.

  • Related