SoFunction
Updated on 2025-03-09

Methods using return and exit in shell scripts

Shell scripts are like using return and exit

Return and exit have their own uses. Reasonable use can make shell programming more standardized and controllable.

1. Exit and return basics

1. return is a keyword; exit is a function.
2. Return is the programming language level, which represents the return of the call stack; exit is the system call level, which represents the end of a process.
3. Return is the exit of the function (return); exit is the exit of the process.

exit 0
Run the program normally and exit the program. Use echo $? to return 0, which means that the calling environment believes that your program is executed normally.
exit 1
Abnormal operation causes exit from the program, which can also be other numbers, such as exit -1. The system program has a conventional meaning for program operation errors. Not being 0 means an error in the program operation. The calling environment determines whether your program is running normally based on this return value.

return 0 is used in a function, indicating that the function executes successfully and returns 0; while exit 0 means that the current program executes successfully and directly exits the current execution script or program.

return -1 means that the function fails to execute and returns an error; exit 1 (or greater than 1) means that the program fails to execute and exits the program.

Summary: exit is used to exit the entire shell script process.

Example of EXIT exit instruction

The "exit" command is one of the most common ways to terminate a Bash shell script. It allows the script to exit at any time during execution, and can use an optional exit code to indicate the reason for the script to terminate.

# Check if a file existsif [ -f "" ]; then
  echo "The file exists"
  exit 0 # Exit successfullyelse
  echo "The file does not exist"
  exit 1 # Exit exception with instructionsfi

In this example, the script uses the "-f" test operator to check if a file named "" exists. If the file exists, the script prints a message to the console and exits with success code 0 using the "exit" command. If the file does not exist, the script prints a different message and exits with error code 1.

The "exit" command can also be used to handle errors or unexpected situations during script execution. For example, suppose a script needs to access resources that may not be available, such as a network service or a database. In this case, the script can be terminated gracefully with an error message and an appropriate exit code using the "exit" command.

Example of using return statement in function exit

#!/bin/bash
# Define a function and return the sum of numbersfunction add_numbers {
  local num1=$1
  local num2=$2
  local sum=$((num1 + num2))
  return $sum
}
# Call the function and print the resultread_file ""
# Call the function and print the resultadd_numbers 3 71
result=$?
echo "3 + 71 = $result" 

In this example, the script defines a function called "add_numbers" that takes two parameters and returns their sum. Inside the function, use the "return" command to exit with the sum as the return value.

**The "return" command can also be used to handle errors or unexpected situations inside functions. **For example, suppose a function needs to read data from a file, but the file does not exist. In this case, the function can exit with an error code and an error message using the "return" command.

#!/bin/bash
# Define a function to read a filefunction read_file {
  local file=$1
  if [ ! -f "$file" ]; then
    echo "Error: File $file not found"
    return 1
  fi
  cat $file
}

If the file does not exist, the function prints an error message andReturns an error code 1, which can be used by the calling script or process to handle the error accordingly.

** Using the "return" command inside a function is a great way to correctly exit the function and communicate its results to other parts of the script or to the calling process. **By using the appropriate return value and error code, the script can handle unexpected situations and improve its overall robustness and reliability.

2. Best practices

  • Functions must be exited using return and cannot be exited.
  • The script body logic uses return to set the exit code, and finally exit the script.
  • If you need to accurately control the exit code, it is recommended to use return for logic in the script.
  • When an unprocessable error occurs, you can directly terminate the script with exit.

3. The problem of the master control script exit interrupt when the subscript returns a non-zero status code.

Problem description

Main control script A, loop calls subscripts B and C, executes subscript B exit, and finds that main control script A has been interrupted loop, and subscript C is not called

[Important] Analysis of issues

At first I thought: exit would cause the entire script process to end and the main control script loop would also be interrupted. The test found that the subscript exit is non-zero, which will cause the master control script to exit directly.

In fact, I finally found that it was my main control log printing. According to the $? of the subscript, it was not that the subscript exited itself when it was not 0. It was not that the subscript exited not 0, and the main control would definitely exit! ! ! It's an obscene ~

Conclusion: The exit of the subscript will not directly cause the main script to exit. The main program must process $? and decide on the next step.

However, here we can summarize the following 2 more useful shell practice techniques:

  • Make good use of exit $?
  • Use sh tone scripts

Use function + return to return, and finally exit $? to exit the script in the end

Complete example demo:

start_mongodb(){
  $MONGODB_BIN_DIR/mongod -f $MONGO_CONF
  if [ $? -eq 0 ]; then
    echo "MongoDB started successfully"
    return 0
  else
    echo "Failed to start MongoDB"
    return 1
  fi
}
stop_mongodb(){
  $MONGODB_BIN_DIR/mongod -f $MONGO_CONF --shutdown
  if [ $? -eq 0 ]; then  
    echo "MongoDB stopped successfully"
    return 0
  else
    echo "Failed to stop MongoDB"
    return 1  
  fi
}
status(){
  if [ -f $MONGODB_PIDFILE ]; then
    echo "MongoDB is running, PID: $(cat $MONGODB_PIDFILE)"
    return 0
  else
    echo "MongoDB is stopped"
    return 1
  fi
}
function control_mongodb(){
  case $1 in
    start)
      start_mongodb  
      ;;
    stop)
      stop_mongodb
      ;;
    restart)
      stop_mongodb
      start_mongodb
      ;;
    status)
      status
      ;;
    *)
      echo "Usage: $0 {start|stop|restart|status}"
      exit 1
  esac
  return $? 
}
# Call functioncontrol_mongodb $1
exit $?

In Linux shell scripts, exit $? means to use the exit status code of the previous command to exit the current shell script. $? is a special variable that savesExit status code of the previous executed command or function. Exit status code 0 indicates successful execution, and non-0 usually indicates failure or error. The specific function of exit $? is:

  • $? Get the exit code of the previous command
  • exit to exit the script
  • Use the exit code of the previous command as the final exit code of the script

Things to note when using sh tone scripts

Using sh tone scripts, there are usually several usage scenarios:

Force the subscript to run in a clean environment.

  • sh A new shell instance will be started, and no custom settings, variables, etc. of the current shell will be inherited, which can provide a clean and isolated running environment.
  • Sets a specific shell for the subscript. When calling subscripts directly, the current shell (usually bash) is used, but sometimes it needs to be specified as sh, csh and other shells.
  • When changing the directory in the script, the subscript is called using the relative path.
  • sh Reset the working directory so that the relative path takes effect.
  • When a subscript needs another version of the shell. Directly call inherits the current shell, but sh can specify the required shell.
  • When upgrading the system shell, ensure that the subscripts are backward compatible. It may be an error to call directly to use the new shell, but the sh call can keep the original shell.
  • For security reasons, do not trust subscripts, use sh sandbox isolation
  • Calling scripts in daemons requires a clean and predictable new shell environment. Some old scripts rely on sh calls, and direct conversion will destroy the original behavior.

In short, the use of sh calls is mainly to finely control the execution environment of the subscript and meet specific compatibility requirements. But when usually needed, it is easier to call directly.

In fact, in general, it is not recommended to use sh because sometimes there will be problems with the sh tone script. For example, when sh executes the script, the kill command has an error of illegal options.

There are some subtle differences between dash and bash in handling kill command options. dash does not support kill commands without parameters, nor does it support kill -s signal mode, and the signal name needs to be written directly. So it can be executed normally under bash:

kill -SIGTERM pid
kill -s TERM pid 

But under dash, it needs to be written as:

kill -TERM pid

Your script itself has no problem, but when called via sh, the use of dash restrictions leads to an error. It can be modified to call the script directly without using sh:

./nginx_ctrl.sh stop

Or use kill -TERM instead of kill -s TERM in scripts.This shell difference can attract attention. If it is compatible with sh/dash, the following parameter format needs to be adjusted.

You can use the following methods to determine what the system default sh shell is:

1. Run sh directly to see what shell you enter by default:

$ sh
$ echo $SHELL
/bin/dash

If it is printed out as /bin/dash, then the default is dash.

2. View the file pointed to by the symbolic link of /bin/sh:

$ ls -l /bin/sh
lrwxrwxrwx 1 root root 4 Mar 15  2020 /bin/sh -> dash

If it points to dash, it means that the default is dash.

Ubuntu and Debian are dash by default.

This is the end of this article about shell scripts such as using return and exit. For more relevant shells using return and exit, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!