Friday, 25 April 2008

Gracefully exit a bash script on ctrl+C

If a user presses control+c to exit your bash script you may wish for the script to preform some tasks before exiting. To do this you can trap the command. You can use trap along with a function to print a message to the user as follows:

trap stopScript INT
stopScript() {
  echo "Exiting script due to user pressing ctrl+c"

  exit
}

By not putting an exit in your function will cause the script to continue, ignoring the ctrl+c from the user.

Tuesday, 15 April 2008

Reading from and sending data to the COM port in Bash

To read data that is coming from your COM port you need to know what the correct device is. Usually this is in /dev and is called something like /dev/ttyS0. To send data to the COM port simply redirect the output of an echo to the device:
echo "ping 192.168.1.1" > /dev/ttyS0
This will send the command ping 192.168.1.1 across the COM port to the device.

If you want to read from the COM port you need to concatenate the device:
cat /dev/ttyS0
This command will hand and any data will be printed to your console

Wednesday, 2 April 2008

Creating multiple subdirectories at once

If you want to create a directory with many parent directories that don’t already exist it can be a pain to create each directory one at a time. mkdir provides the flag -p to create all the directories if they don’t already exist to speed this process up and make it less tedious.

To make its use clear here is an example:
user@computer:~> mkdir -pv /tmp/test/directory/subdirectory1/subdirectory2
mkdir: created directory `/tmp/test’
mkdir: created directory `/tmp/test/directory’
mkdir: created directory `/tmp/test/directory/subdirectory1′
mkdir: created directory `/tmp/test/directory/subdirectory1/subdirectory2