function::exit - Linux


Overview

The function::exit command in Linux provides a controlled method to exit a function defined in a script. It allows for graceful handling of errors or unexpected behavior by prematurely terminating the function’s execution.

Syntax

function::exit [EXIT_CODE]

Parameters:

  • EXIT_CODE (Optional): Integer exit code to return upon exiting the function. Defaults to 0 if omitted.

Options/Flags

None

Examples

Example 1: Exit with a custom exit code:

function my_function() {
  echo "Performing some task"
  if [ $? -ne 0 ]; then
    function::exit 1
  fi
  echo "Task completed successfully"
}
my_function

Example 2: Exit with default exit code (0):

function my_function() {
  echo "Performing another task"
  function::exit
}
my_function

Common Issues

Error: function::exit: command not found

  • Solution: Ensure that the script containing the function definition is sourced or executed using the source or . commands.

Error: function::exit: not within a function

  • Solution: The function::exit command can only be used within a function definition.

Integration

function::exit can be used in conjunction with other commands or tools to handle errors and exceptions in scripts:

  • Combine with if statements: Exit a function with an error code based on the result of an if statement condition.
  • Use in error handling routines: Define a function as an error handler and use function::exit to terminate the script with an appropriate exit code.
  • Integrate with logging tools: Use function::exit to terminate a function and write an error message to a log file before exiting the script.

Related Commands

  • exit: Exits the entire script with a specified exit code.
  • return: Exits the current function without terminating the script.