Command line beep using Bash

Table of Content

I wanted to make a little script that could make a beep or some fun sound when a long-running terminal process was complete… Because who sits there and watches the terminal all day when we have websites to browse and applications to write?

I found a little script on StackExchange which would produce a simple beep by running a command like "_alarm 400 200". The command uses an underscore to denote that it’s a custom function, in case there’s another application called "alarm".

I then created a command called "jobdone" which runs several synchronous instances of the _alarm command to create a short song. To me it sounds like "♫ the job is done ♫". You can modify the numbers or create your own methods with their own alarm commands to create custom tones.

  1. Open your .bashrc file under ~/.bashrc
$ gedit ~/.bashrc
  1. Add the following code to the end of the file:
# code from http://unix.stackexchange.com/a/163716 
# modified by Allan Bogh 
_alarm() { 
  ( \speaker-test --frequency $1 --test sine )& 
  pid=$! 
  \sleep $(bc -l <<< ${2}/1000)s 
  \kill -9 $pid 
}

# code from https://allanbogh.com/2016/01/04/command-line-beep-using-bash/ 
jobdone() { 
  _alarm 800 150 && _alarm 900 150 && _alarm 1000 150 && _alarm 1200 300 
}
  1. Open a new terminal window and type the function name:
$ jobdone

# or use it with another long-running command 
$ someCommand && jobdone 

# for example 
sleep 10s && jobdone

Try using the command "jobdone" in the terminal by itself, then play around with "_alarm 800 200" by changing the 2 numbers.

Fun test!

Here’s a script I wrote which plays a fun song. Can you guess which song I created? To execute this, copy the functions into your .bashrc file using the instructions above, then use the "funsong" command in a new terminal window!

_mySong() { 
  #staff 1 
  _alarm 196.00 150 && _alarm 261.63 150 && _alarm 329.63 150 && _alarm 392 150 && _alarm 523.25 150 && _alarm 659.25 150 && _alarm 783.99 500 && _alarm 659.25 500 

  #staff 2 
  _alarm 207.65 150 && _alarm 261.63 150 && _alarm 311.13 150 && _alarm 415.30 150 && _alarm 523.25 150 && _alarm 622.25 150 && _alarm 830.61 500 && _alarm 622.25 500 

  #staff 3 
  _alarm 233.08 150 && _alarm 293.66 150 && _alarm 349.23 150 && _alarm 466.16 150 && _alarm 587.33 150 && _alarm 698.46 150 && _alarm 932.33 500 && _alarm 987.77 150 && _alarm 987.77 150 && _alarm 987.77 150 && _alarm 1046.50 1000 
} 

funsong() { 
  _mySong & 
  sleep 0.015s 
  _mySong & 
  sleep 0.03s 
  _mySong & 
  wait echo "Can you guess which song this was?" 
  echo "Visit https://allanbogh.com/2016/01/04/command-line-beep-in-ubuntu/ and leave a comment." 
}

Leave a Reply

Your email address will not be published. Required fields are marked *