1

I am playing with perl's system function but I am confused of what is the return value of this function. Consider following examples:

[wakatana@arch ~]$ grep root /etc/passwd
root:x:0:0:root:/root:/bin/bash
[wakatana@arch ~]$ echo $?
0
[wakatana@arch ~]$ grep roots /etc/passwd
[wakatana@arch ~]$ echo $?
1

[wakatana@arch ~]$ perl -e 'my $code = system("grep root /etc/passwd 2>&1 1>/dev/null"); print $code . "\n"'
0
[wakatana@arch ~]$ perl -e 'my $code = system("grep roots /etc/passwd 2>&1 1>/dev/null"); print $code . "\n"'
256

Why is the second perl returning 256 instead of 1 ?

Here is excerpt from perldoc:

"Return value of -1 indicates a failure to start the program or an error of the wait(2) system call (inspect $! for the reason)"

It seems that something went wrong during execution of external command so I've also tried following commands to figure out what is going on, but I am still lost.

# Seems that regular bash command, in this case exit, is equivalent to blablabla
[wakatana@arch ~]$ perl -e 'my $code = system("exit 2"); print $code . "\n"'
-1
[wakatana@arch ~]$ perl -e 'my $code = system(blablabla); print $code . "\n"'
-1
[wakatana@arch ~]$ perl -e 'my $code = system("grep roots /etc/passwd 2>&1 1>/dev/null") or die $!'
[wakatana@arch ~]$

Can somebody please explain this behavior.

@EDIT in reply to: Paul Roub and ikegami

Mystery solved:

2[wakatana@arch ~]$ perl -e 'my $code = system("bash -c \"exit 2\""); print $code >> 8; print "\n"'
2
[wakatana@arch ~]$ perl -e 'my $code = system("exit 2"); print $! . "\n"'
No such file or directory
[wakatana@arch ~]$ perl -e 'my $code = system(blablabla); print $! . "\n"'
No such file or directory
[wakatana@arch ~]$ perl -e 'my $code = system("grep roots /etc/passwd 2>&1 1>/dev/null"); print $code >> 8; print "\n"'
1
Wakan Tanka
  • 7,542
  • 16
  • 69
  • 122
  • 8
    The doc you linked continues: "The return value is the exit status of the program as returned by the wait call. To get the actual exit value, shift right by eight (see below). " In your case, `256 >> 8` is `1`. – Paul Roub Feb 09 '15 at 15:50
  • @Paul Roub Oh I see, thank you very much. Can you please explain why `system("exit 2")` returns -1 one thing that comes to my mind right now is because exit is bash internal command. Am I right? – Wakan Tanka Feb 09 '15 at 16:33
  • 3
    That is also in the documentation for [`system`](http://perldoc.perl.org/functions/system.html). -1 means `system` itself failed, and the error is in `$!`. In this case, it's probably an inability to find an executable named `exit`. – ikegami Feb 09 '15 at 16:41

0 Answers0