Velvet Star Monitor

Standout celebrity highlights with iconic style.

news

On a linux shell, what is echo $? supposed to do?

Writer Sophia Terry

I came across a shell script where echo $? was used. What does this mean . How can we use this in a shell script. Are there any references for this.

2 Answers

echo $? means status of your previous command

see the example here

[root@localhost ~]# jk
-bash: jk: command not found
[root@localhost ~]# echo $?
1
[root@localhost ~]# pwd
/root
[root@localhost ~]# echo $?
0
[root@localhost ~]# 

At first you are getting 1 because command is wrong And second time you are getting 0 because command was successful

There is no command called jk (in my case)

$? returns the result of the last run command in a bash (and probably other) shell.

From example 6-1:

#!/bin/bash
echo hello
echo $? # Exit status 0 returned because command executed successfully.
lskdf # Unrecognized command.
echo $? # Non-zero exit status returned -- command failed to execute.
echo
exit 113 # Will return 113 to shell. # To verify this, type "echo $?" after script terminates.
# By convention, an 'exit 0' indicates success,
#+ while a non-zero exit value means an error or anomalous condition.
# See the "Exit Codes With Special Meanings" appendix.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy