Search code examples
shellcshexit-code

If else loop not working in csh shell script


This is sample perl code. abc.pl

my $a=0; my $b=0; my $c=0;
my $sum = $a+$b+$c; $ex = 0;
if($sum == 0){
    print "success"; print " $ex \n";
}else{
    $ec=1 ; print "Not success"; print " $ex \n";
}
exit $ex;

This is my shell script

set ecd = `abc.pl`
set status = $?
echo $status
if ( $status == 0 ) then
    echo "Here Status is $status"
else
    echo "Status is $status"
endif
echo $status

Now I have problem with if else loop, The value of status seems to change before and after the if loop, everytime it prints only the msg in if condition. Sample output.

1 
Here Status is 0 
0 

Please help to correct this. I think the status if reflecting the prev command if ? Please suggest how can I make this if loop work correctly. Please suggest me how I can get better with the basics aswell. Help is very much appreciated. Thanks a lot in advance. This is continuation to the question : [https://stackoverflow.com/questions/75523005/how-to-capture-exit-code-of-a-perl-script-which-is-called-from-a-shell-script][1]


Solution

  • Not familiar with csh but I believe $status is a csh's special variable that is equivalent to $?.

    So the $status in if statement at line 4 will be updated by the exit code of echo $status at line 3, as always equals to 0.

    Try changing your $status variable with $rc or anything else.

    I'd rather recommend you to rewrite your shell script with bsh/bash though.