HOME BLOG

Archive for the ‘Shell script’ Category

How to execute shell scripts that can throw an error without causing Jenkins build to fail

Posted on: October 1st, 2022 by Olu No Comments

Hi folks,

Usually, if a shell script in a Jankins build throws an error, the build fails automatically. In this post I talk briefly about a technique for running a shell script in your Jenkins CI pipeline without causing the build to fail if the shell script throws an error.
The technique is to use code like the following:

sh("""
set +e
/your/script/that/may-or-may-not-fail.sh
set -e
""")

 

set +e is the default way that bash runs. That is, if a command throws an error, bash displays it, but continues with the script.

set -e forces the script to exit if there’s an error.

That’s all for now. Till next time, happy software development.

How to get process id of last executed background process in Shell script

Posted on: August 10th, 2021 by Olu No Comments

Hi folks,

In this short post I will describe how to get the process id of the last process that was executed in the background.

You do that using the symbol $!

E.g. If you run the commands:

date &
echo $!

you will get an id like 12345 corresponding of the process id for the date command you ran in the background previously.

The process id of the last run background process could be very useful if you want to do things like killing the process when a certain condition is meant. For example, when deploying multicontainer pods in Kubernetes using the sidecar pattern, you may want to terminate the sidecar container once the main container’s process finishes. One way to do this is in the sidecar is to start the sidecar process in the background, fetch its process id, wait for a trigger file which will be written by main container to signal process completion, then kill the sidecar process once the trigger file is found.

See the article How to terminate a side-car container in Kubernetes Job [1] for details.

That’s all for now. Happy software development.

 

Reference

1. How to terminate a side-car container in Kubernetes Job https://cotton-ori.medium.com/how-to-terminate-a-side-car-container-in-kubernetes-job-2468f435ca99

2. Does $! mean something in shell scripting. Stackoverflow. https://stackoverflow.com/questions/18462916/does-mean-something-in-shell-scripting