What is the $? (dollar question mark) variable in shell scripting? [duplicate] What is the $? (dollar question mark) variable in shell scripting? [duplicate] shell shell

What is the $? (dollar question mark) variable in shell scripting? [duplicate]


$? is used to find the return value of the last executed command.Try the following in the shell:

ls somefileecho $?

If somefile exists (regardless whether it is a file or directory), you will get the return value thrown by the ls command, which should be 0 (default "success" return value). If it doesn't exist, you should get a number other then 0. The exact number depends on the program.

For many programs you can find the numbers and their meaning in the corresponding man page. These will usually be described as "exit status" and may have their own section.


A return value of the previously executed process.

10.4 Getting the return value of a program

In bash, the return value of a program is stored in a special variable called $?.

This illustrates how to capture the return value of a program, I assume that the directory dada does not exist. (This was also suggested by mike)

        #!/bin/bash        cd /dada &> /dev/null        echo rv: $?        cd $(pwd) &> /dev/null        echo rv: $?

See Bash Programming Manual for more details.