


Checking whether the command is successful in Bash can be achieved by exiting the status code. 0 indicates success, non-zero value indicates error; use $? to view the exit code of the previous command, such as ls /some/directory; echo $?; or it can be directly judged in the if statement, such as if mycommand --option; then echo "Success"; else echo "Failed"; fi; Common exit codes include 0 (success), 1 (general error), 2 (incorrect command usage), etc.; use set -e to make the script exit immediately when any command fails, but be used with caution to avoid misjudgment of non-serious errors.
In Bash, checking whether a command succeeded is straightforward: you look at its exit status. By default, a command returns 0
if it succeeded and a non-zero value (usually 1
, but sometimes others) if something went wrong.
Here's how to check it in your scripts or on the command line.
Using $?
to check the exit code
After running any command in Bash, you can immediately check the special variable $?
. It holds the exit status of the last command executed.
For example:
ls /some/directory echo $?
- If
ls
found the directory and listed it, you'll see0
. - If the directory doesn't exist or there was a permission issue, you'll get a number like
2
.
This method works well in scripts when you want to conditionally do something based on success or failure.
A simple usage in a script:
#!/bin/bash mycommand --option if [ $? -eq 0 ]; then echo "Command succeeded" else echo "Command failed" fi
Just remember — once another command runs after the one you care about, $?
gets overwritten. So use it right away.
Using if
directly with the command
Instead of using $?
, you can put the command directly inside an if
statement. This is cleaner and avoids possible mistakes from forgetting that $?
changes quickly.
Here's how that looks:
if mycommand --option; then echo "Success!" else echo "Failed!" fi
This is often preferred because:
- It's more readable.
- You don't have to manually compare numbers.
- Less chance of accidentally using the wrong
$?
.
You can also chain this with other logic, like retrying a command or logging errors.
Common exit codes and what they mean
Exit codes are defined by each command, but some are standard:
-
0
= Success -
1
= General error -
2
= Misuse of shell builtins (like incorrect options) -
126
= Command found but not executed -
127
= Command not found -
130
= Script interrupted (eg, Ctrl C pressed)
These aren't always consistent across all programs, but they give a general idea of ??what went wrong.
If you're debugging a script or trying to understand why something didn't work, checking these values ??can help pinpoint the issue.
Use set -e to exit on error in scripts
If you're writing a script and want it to stop as soon as any command fails, add this at the top:
#!/bin/bash set -e
This tells Bash to exit immediately if any command exits with a non-zero status. It's useful for automation where partial execution might leave things in an inconsistent state.
But be careful — sometimes commands return non-zero even when it's not a serious problem. For example, grep
returns 1
if it finds no matches, which isn't always an error.
So, use set -e
wisely, especially if you're relying on certain commands to run even if previous ones fail.
That's basically it. Checking if a command succeeded in Bash comes down to understanding exit codes and knowing how to access or act on them — either through $?
, direct conditions, or script flags like set -e
.
The above is the detailed content of How to check if a command succeeded in bash. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

ArtGPT
AI image generator for creative art from text prompts.

Stock Market GPT
AI powered investment research for smarter decisions

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Windows Subsystem for Linux The first option is to use Windows Subsystem for Linux or WSL, which is a compatibility layer for running Linux binary executables natively on Windows systems. It works for most scenarios and allows you to run shell scripts in Windows 11/10. WSL is not automatically available, so you must enable it through your Windows device's developer settings. You can do this by going to Settings > Update & Security > For Developers. Switch to developer mode and confirm the prompt by selecting Yes. Next, look for W

At the beginning of this year, when Microsoft and Canonical released Windows 10 Bash and Ubuntu user space, I tried to do some preliminary performance tests on Ubuntu on Windows 10 compared to native Ubuntu. This time I published more about the benchmark comparison between native pure Ubuntu and Windows 10. The Linux subsystem test for Windows completed all tests and was released with the Windows 10 Anniversary Update. The default Ubuntu user space is still Ubuntu14.04, but it can be upgraded to 16.04. So the test is first tested on 14.04, and after completion, the system will be upgraded to 16.04

Here we will see how to get the number A raised to the power B using a bash script. The logic is simple. We have to use the "**" operator or the power operator to do this. Let us see the following program to understand this concept clearly. Example#!/bin/bash#GNUbashScripta=5b=6echo "$(($a**$b))" output 15625

Programmers often use the Bash command language to create shell scripts to automate manual tasks. For example, they create Bash scripts for various configurations, file operations, generating build results, and various DevOps-related activities. Almost all Unix-like or Unix-based operating systems provide users with a pre-installed Bash interpreter, so we can use Bash to write more portable automation scripts. As we already know, Bash scripting refers to writing a series of commands using the syntax of the Bash command language, built-in Bash commands, and core operating system CLI programs such as GNU Core Tools. A standard and old-fashioned Bash script usually executes some commands and displays plain text on the terminal

BourneAgainShell (BASH for short) is the most popular SHELL implementation on GNU/Linux. It was born in 1980. After decades of evolution, it has evolved from a simple terminal command line interpreter into a multi-functional interface deeply integrated with the GNU system. . Bash, a type of Unix shell. The first official version was released in 1989. It was originally planned to be used on the GNU operating system, but it can run on most Unix-like operating systems, including Linux and MacOSXv10.4, which use it as the default shell. It has also been ported to Cygwin and MinGW on Microsoft Windows, or can be used on MS-

Last week Microsoft announced BugBash, a campaign designed to engage Windows insiders with tasks to (hopefully) improve Windows 11 development in the long and short term. Originally on March 16, there were around 26 missions available to complete, but that has now grown to a staggering 75. Here's the kicker, though: BugBash will end on March 22nd, along with the opportunity to earn BugBash-specific stickers that will appear in your Feedback Hub. To participate in the Windows11 BugBash, you need to grab the latest Windows 11 preview build from the Dev channel, which is build2

Bash (also known as GNUbash) is a command language and Unix shell script, a command line interpreter for operating systems. Designed by Brian Fox, it is a free software alternative to Bourneshell. It was first released in 1989 and became the login shell of choice for macOS, Linux-based operating systems, and other Linux-based software. A prime number is a number with only two factors, the number itself and 1. For example, 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, etc. Here, we are given a number and need to determine whether the given number is a prime number. Input:AnumberOutput:&l

Having a solid foundation in programming is obviously an essential quality for a good software engineer. Whether it's an interpreted language like Python or a compiled language like C++, it's crucial to master at least one programming language. However, this is only one aspect of becoming a truly well-rounded engineer. If you lose your way in the shell environment, those basic knowledge will be useless. Flexible use of commands in Bash will take you to areas that traditional programming languages ??cannot reach. Sometimes, you don't actually need to use a more powerful programming language. By using just the Shell, you can accomplish the tasks you need faster and easier, and without the need for additional dependencies. In this article, we will explore some very useful Bash commands
