4

I know the return code will be contained in $? after a command was executed, but what does $? mean after a script was executed? The return code of the last command in that script?

Can I tell if a script has been excuted from head to tail and not interrupted by some unexpected system halt or something?

If I have a script like below excuted,

Command A;
if [ $? -eq 0]
then
echo "OK" >> log
else
echo "failed" >> log
fi

and the system halted while A was running, what will I find in that log file? "OK", "failed" or nothing?

3 Answers 3

6
  1. Yes, or the value passed after exit, e.g. exit 31.

  2. Not without taking measures within the other script to make it explicit.

Sign up to request clarification or add additional context in comments.

2 Comments

If the other script was terminated by an interrupt, the exit status reported to the shell will not be zero (unless the script handled or ignored the interrupt and arranged for a zero exit after all). If the system halted, the calling script got halted too - there is no chance of determining anything unless you have a very sophisticated system for handling retries, etc.
Note that if the last command the script executes isn't exit (e.g. if it exits because it ran into the end of the script file, or exited early due to set -e and an error), the return code of the script will be the return code of the last command it executed.
4

$? reads the exit status of the last command executed. After a function returns, $? gives the exit status of the last command executed in the function. This is Bash's way of giving functions a "return value.

Example

#!/bin/bash

echo hello
echo $?    # Exit status 0 returned because command executed successfully.

lskdf      # Unrecognized command.
echo $?    # Non-zero exit status returned because 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

Comments

0

the return code of the script is indeed the return code of the last command executed, some commands allow you to finish execution at any point and arbitrarily set the return code; those are exit for scripts and return for functions but in both cases if you omit the argument they'll just use the return code of the previous command.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.