Questão de Linux Administration #019e3987
When the command echo $ outputs 1, which of the following statements is true?
It is the process ID of the echo command.
It is the process ID of the current shell.
It is the exit value of the command executed immediately before echo.
It is the exit value of the echo command.
Explicação Oficial / Explicações da Comunidade
The command echo $? outputs the exit status of the last executed command. In this case, echo $? outputs 1, which indicates that the command executed immediately before echo exited with a non-zero status (typically indicating an error). The $? variable is a special shell variable that holds the exit code of the most recently executed foreground pipeline.
How it Works
- Every command in Unix/Linux returns an exit status (integer) to the shell upon completion. By convention,
0means success, and any non-zero value (1-255) indicates an error or abnormal termination. - The shell stores this exit status in the
$?variable immediately after the command finishes. - Running
echo $?prints the value of$?, which is the exit status of the previous command.
Why the Correct Value is Right
The statement "It is the exit value of the command executed immediately before echo" is correct because $? always reflects the exit status of the last command that was executed. If the previous command failed (e.g., ls /nonexistent), $? would be non-zero, such as 1.
Why the Incorrect Values are Wrong
- "It is the process ID of the echo command": The process ID (PID) of a command is obtained via
$$(current shell PID) or$!(last background process PID), not$?.$?holds exit status, not PID. - "It is the process ID of the current shell": The current shell's PID is stored in
$$, not$?.$?is unrelated to process IDs. - "It is the exit value of the echo command": The
echocommand itself almost always succeeds (exit status 0) unless a write error occurs. The output1comes from the command that ran beforeecho, not fromechoitself. Afterechoruns,$?would be0(assuming success), so the value1must be from an earlier command.