How can the shell retrieve the return value of a function?

In a shell script, you can use $? to get the return value of a function. After the function finishes execution, it will return a numeric value, typically 0 for success and a non-zero value for failure. You can use $? to retrieve the return value of the function and determine if the function execution was successful. Here is an example code:

#!/bin/bash

my_function() {
    # 执行一些操作
    return 1
}

my_function
result=$?

if [ $result -eq 0 ]; then
    echo "Function executed successfully"
else
    echo "Function failed"
fi

In the example above, the my_function function returned 1, indicating that the function execution failed. $? retrieves the return value of the function and displays the corresponding message based on the return value.

bannerAds