What Does echo $? Do it in Linux?

In Linux when the command is executed, there are two possibilities, either it will be executed successfully or failed. The successful/failed status of the command execution is stored in the built-in “$?” variable. It is helpful for the user to check any command execution status to perform other tasks based on the output.

This will describe the purpose of the “$?” mark in Linux.

“echo $?” in Linux

As described earlier, “$?” stores the last command execution status, it shows the status in “0” for successful execution and “1” for failed execution of the command. Let’s implement some examples to understand this.

Example 1: Displaying “0” Status of Previous Command 

To check the successful ”0” status of command execution, open the bash script file with nano editor and add the following script:

$ nano script.sh
#!/bin/bash
ls
echo $?

The script is defined as:

  • #!/bin/bash” defining the bash script.
  • “ls” command to execute.
  • echo” statement to print the “$?” for status.

Save the file by pressing “Ctrl+O” and exit from the file using “Ctrl+X

Run the bash script file (script.sh) by running the following command:

$ bash script.sh

The command executed successfully and has returned the “0” status.

Example 2: Displaying “1” Status of Previous Command 

Likewise, to check the failure status “1” of the command, let’s run the wrong command in the bash script as shown:

#!/bin/bash
cd downloads
echo $?

The script is defined as:

  • #!/bin/bash” defining the bash script.
  • cd download” command to execute.
  • echo” statement to print the “$?” for status.

Save the above script file.

Run the “script.sh” file through the given command:

$ bash script.sh

The command execution failed as there is no “download” directory exists and has returned the status of “1”, as shown in the above image. 

Example 3: Displaying Command Execution Status Using if/else

To display the command execution through an if/else statement, run the following script:

#!/bin/bash

ls -a
if [ $? -eq 0 ]; then
    echo "Command executed"
else
    echo "Command Failed"
fi

The script is defined as:

  • #!/bin/bash” defining the bash script.
  • ls -a” command to execute.
  • If” statement checking if the “$?” has the 0 status value and printing message with “echo”.
  • else” statement if the above “if” statement failed.
  • fi” closing if statement.

Save the above file script.

Run the script file to check the results:

$ bash script.sh

The “ls -a” command executed successfully and has displayed the message “Command executed”.

Conclusion

In Linux, the “$?” is the special variable that stores the execution status of the last command in terms of “1” and “0”. “1” shows the failure execution status while “0” shows the successful execution status of the command. This write-up has illustrated the purpose and use of the “$?” variable in Linux.