how to call linux bash command ang get return code
- User
how to call linux bash command ang get return code
- Assistant
In a Linux environment, you can run a Bash command and capture its return (exit) code using the special variable
$?. Here's how you can do it:Step-by-step Instructions:
-
Open your terminal.
-
Run your command. For example, to check if a directory exists, you can use
ls:ls /path/to/directory -
Immediately check the exit code:
echo $?
Example Script
You can create a simple Bash script that runs a command and captures its exit code:
#!/bin/bash # Run a command (for example, trying to list a non-existing directory) ls /path/to/non-existing-directory # Get the exit code of the last command exit_code=$? # Check the exit code if [ $exit_code -eq 0 ]; then echo "Command succeeded!" else echo "Command failed with exit code: $exit_code" fi -