Question Mark Environment Variable in Linux

By | October 25, 2021

Question Mark Environment Variable is special variable in Linux and other Unix operating systems which contains status (return code) of shell commands or executable. This variable is widely used in scripts to verify exit status of shell command. The value range of question mark environment variable is between 0 and 255. Normally zero value means that command was completed successfully without errors. The example with ls command:


% ls /Applications/Docker.app
Contents

The ls command above was completed successfully and ? variable has 0 value.


% echo $?
0

The next example when ls command was completed with error:


% ls /Applications/Dcker.app
ls: /Applications/Dcker.app: No such file or directory

The result is different than zero:


% echo $?
1

TTL of ? variable value is short, any next command will update ? variable value, `even echo $?` command does it:


% ls /Applications/Dcker.app
ls: /Applications/Dcker.app: No such file or directory
% echo $?
1
% echo $?
0

If you want to use value of ? variable later after execution of several commands the current value of ? variable should be saved somewhere:


% ls /Applications/Dcker.app
ls: /Applications/Dcker.app: No such file or directory
% export LSRET=$?
% echo $?
0
% echo $LSRET
1

If executable return value is more than 255 only lowest 8 bits are saved in ? variable. This is the code:


#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(int n, char ** s)
{
   srand(time(NULL));
   int randval = rand();
   printf("Return value: %x\n", randval);;
   return randval;
}

Result:


% ./randomret
Return value: 40ee849c
% echo $(([##16]$?))
9C

Leave a Reply

Your email address will not be published. Required fields are marked *