Linux Administration
medium

Questão de Linux Administration #019e3987

Enunciado da Questão
Linux Administration
#echo
#dollar-question-mark
#exit-status
#shell-variable
Médio

When the command echo $ outputs 1, which of the following statements is true?

A

It is the process ID of the echo command.

B

It is the process ID of the current shell.

C

It is the exit value of the command executed immediately before echo.

Correta
D

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, 0 means 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 echo command itself almost always succeeds (exit status 0) unless a write error occurs. The output 1 comes from the command that ran before echo, not from echo itself. After echo runs, $? would be 0 (assuming success), so the value 1 must be from an earlier command.