As a DevOps engineer, or any other Operation roles, we sometimes need to check if a Linux command succeeded. There are many reasons, for example: our internet connection failed, a VPN connection hangs on the remote server while we were running some commands, maybe backing up some MySQL DBs (don’t do manual backups!), or we just want to pass the command exit status as a conditional in an automation script, et al. You get my point. Let’s see how can we check the status of a command while we were kicked out of the server.
- Linux bash environment
Step 1. Connect to the remote server, and let’s update some package information first.
apt update -y
Step 2. Once the command run, execute the following command to check if it was successful.
root@devcoops:~# echo $? 0
Notice the output value is
0. The integer
0 exit status means that the command was successful without any errors.
Step 3. But, what if we interrupt the
apt update -y while it’s running. Run
apt update -y again and interrupt it, by pressing
Ctrl + C.
root@devcoops:~# apt update -y 0% [Working]^C root@devcoops:~# echo $? 130
As you can see the output value is
130. This is obviously an error status code. Why
130 though? Well, if a process is killed by signal n, the value is n + 128. SIGINT or Signal Interrupt as the name suggests, will interrupt any given process, and because it’s numbered as a signal 2 on most Unix variants, thus
$? is 128 + 2 = 130.
As always, use it as a conditional in a bash script, or even better, as part of an Ansible playbook. Feel free to leave a comment below and if you find this tutorial useful, follow our official channel on Telegram.