What does $? mean immediately after trying to execute an invalid command in the Bourne shell?

I know the $? means the return value of the lastly executed command. I was curious; if the command is invalid, then what will $? be?

It was 127. What does it mean? Why is it 127?

> echo a
a
> echo $?
0
> invalidcommandasdf
invalidcommandasdf: not found
> echo $?
127

The Bourne shell

Upvotes: 0

Views: 120

Answers (3)

chepner
chepner

Reputation: 531758

The exit status does double duty: it might return information from a program, but it also might return information from whoever ran the program about how the program exited. While a program can, in theory, have any exit code in the range 0 to 255, many of them are assigned special meaning by, say, the POSIX standard, and are not available for use by the program itself.

126 and 127, for instance, are for use by the shell (or other command runner) running the command. 127 means the command could not be found, and 126 means the command was found, but wasn't executable.

Any exit status greater than 128 indicates the program exited due to a signal: 129 when it exits due to signal 1, 130 due to signal 2, etc. In general, 128 + k means it exited due to signal k.

(I'm not sure if 128 itself is reserved for anything in particular.)

In practice, this means your command should not explicitly use any exit code greater than 125. That generally shouldn't be a problem; most commands don't need to distinguish between 125 different errors (0, of course, means it exited without error.) curl is an example of a program that uses a lot of different codes, but even it only uses most of the available values between 1 and 90.

Upvotes: 1

data-bite
data-bite

Reputation: 417

The primary use of "$?" is to check if the last run command has exit value true or false. You will get output as '0' or '1' where '0' is returned if the last run command is true and '1' if its false.

For unknown commands you will get output such as you have shown. You can try this by simple using random string (sajdgh / uytwegf) as unrecognized commands and you can see you get a different output.

However the primary use of this command is check the logical status of last used command. Fire ls and see the output of "echo $?" will be '0' now just try 'cat unknown.txt' (considering you actually dont have file named 'unknown.txt') you will get output as '1'

Upvotes: 1

Mahendra
Mahendra

Reputation: 1426

$? gives the exist status code of last executed command/process. 127 status code means Command Not found

for more detail : bash-shell-exit-status/

Upvotes: 1

Related Questions