how to check last function return code on bash
- User
how to check last function return code on bash
- Assistant
In Bash, the return code of the last executed command can be checked using the special variable
$?. This variable holds the exit status of the last command executed. An exit status of0typically indicates success, while any non-zero value indicates an error.Here’s how you can check the return code:
# Execute a command some_command # Check the return code if [ $? -eq 0 ]; then echo "Command succeeded" else echo "Command failed with return code: $?" fiAlternatively, you can simplify this by using the
&&and||operators:some_command && echo "Command succeeded" || echo "Command failed with return code: $?"In this example:
- If
some_commandsucceeds (returns a status of0), the message "Command succeeded" will be printed. - If
some_commandfails (returns a non-zero status), the message "Command failed with return code" will show the actual return code.
Remember that
$?must be checked immediately after the command whose return code you want to assess, as executing any other command will overwrite the value of . - If
- User
how to check last function return code on bash terminal
- Assistant
In a Bash terminal, you can check the return code of the last executed function (or command) using the special variable
$?, just like with any other command. Here’s how to do it step-by-step:-
Define a function (if you haven't already):
my_function() { # Some commands here return 1 # or return 0 for success } -
Call the function:
my_function -
Check the return code:
echo $?
The complete example would look like this in the terminal:
# Define a function that returns an error code my_function() { echo "This is my function." return 1 # Simulating an error } # Call the function my_function # Check the return code return_code=$? echo "The return code of my_function is: $return_code" # You can also use an if statement to check the return code if [ $return_code -eq 0 ]; then echo "Function succeeded." else echo "Function failed with return code: $return_code" fi -