Tag Archives: shell


Shell script wrapper function for sending messages through Pushover

Pushover makes it easy to get real-time notifications on your Android, iPhone, iPad, and Desktop (Android Wear and Apple Watch, too!)

You can use this shell function anywhere in your script.



pushmail() {
    curl 'https://api.pushover.net/1/messages.json' -X POST -d "token=$APP_TOKEN&user=$USER_TOKEN&message=\"$MESSAGE\"&title=\"$TITLE\""

# call
pushmail "server is down"

Note: you need to update API tokens and title above

Locking your bash script against parallel execution

Sometimes there’s a need to ensure only one copy of a script runs, i.e prevent two or more copies running simultaneously. Imagine an important cronjob doing something very important, which will fail or corrupt data if two copies of the called program were to run at the same time. To prevent this, a form of MUTEX (mutual exclusion) lock is needed.

The basic procedure is simple: The script checks if a specific condition (locking) is present at startup, if yes, it’s locked – the script doesn’t start.

This article describes locking with common UNIX® tools.

Method 1

setting the noclobber shell option (set -C). This will cause redirection to fail, if the file the redirection points to already exists (using diverse open() methods). Need to write a code example here.

if ( set -o noclobber; echo "locked" > "$lockfile") 2> /dev/null; then
  trap 'rm -f "$lockfile"; exit $?' INT TERM EXIT
  echo "Locking succeeded" >&2
  rm -f "$lockfile"
  echo "Lock failed - exit" >&2
  exit 1


Method 2

A simple way to get that is to create a lock directory – with the mkdir command. It will:

create a given directory only if it does not exist, and set a successful exit code
it will set an unsuccessful exit code if an error occurs – for example, if the directory specified already exists
With mkdir it seems, we have our two steps in one simple operation. A (very!) simple locking code might look like this:

if mkdir /var/lock/mylock; then
  echo "Locking succeeded" >&2
  echo "Lock failed - exit" >&2
  exit 1

In case mkdir reports an error, the script will exit at this point – the MUTEX did its job!

Coloring shell output

Using coloring, we can enhance output of shell script. Run following script in your terminal and see magic.


#various color codes

#ascii art
printf "${color_custom}"
cat <<EOF
   m""                       #                   
 mm#mm   mmm    mmm          #mmm    mmm    m mm 
   #    #" "#  #" "#         #" "#  "   #   #"  "
   #    #   #  #   #   """   #   #  m"""#   #    
   #    "#m#"  "#m#"         ##m#"  "mm"#   # 
printf "${color_no}"