IT Questions and Answers :)

Saturday, June 9, 2018

Which BASH internal variable holds the exit status of the previous command or function?

Which BASH internal variable holds the exit status of the previous command or function?

  • $?
  • $_
  • $@
  • $$ 

 
Which BASH internal variable holds the exit status of the previous command or function?

EXPLANATION

$? is a special variable that is internal to the BASH interpreter. It is used to hold the exit code of the previously executed command or function (or even the script itself).

Example:

#!/bin/bash

/bin/true
echo $? #prints 0

/bin/false
echo $? #prints 1

/bin/foobar
res=$?
if [ $res -ne 0 ]
then
  echo "Command foobar failed to execute or exited with a non-zero status: $res"
else
   echo "Command foobar exited successfully"
fi

Share:

0 comments:

Post a Comment

Popular Posts