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