Bash

How to catch signals in a bash script

POSIX compatible UNIX systems like Linux supports standard signals as part of inter process communication. While some signals like SIGINT can be ignored, SIGKILL and SIGSTOP cannot be caught, blocked or ignored.

Bash provides a command “trap” to assign a signal handler. The following example script catches SIGINT signal that is generally received when user presses Ctrl+C key combination. A bash script will generally terminate on pressing Ctrl+C but it can chose to ignore the signal or do clean up before terminating using signal handler.

#!/bin/bash

trap mysighandler INT

mysighandler()
{
    echo 'You have pressed Ctrl+C.. Ignoring...'
}

for ((i=0;i<10;i++))
do
   echo More >

How to loop or iterate through the output of ls command in a bash script

If your original purpose is to iterate through the list of files and directories present in the current directory, you don’t even have to run ls command for that.

for i in *; do
   echo "$i"
done

Alternately you can use ls to get the list of files and directories as shown below.

for i in `ls`; do
   echo "$i"
done

Other way of writing the above example is:

for i in $(ls); do echo "$i"; done;

The ls command can be used to select files of certain pattern. The following example selects only files will extension “.sh”.

for i in $(ls *.sh); do echo More >

How to print a bash variable along with other text

A general programmer tends to use a simple dollar sign ($) before each variable. However its gets difficult if a variable hash to be echoed along with some other as shown below.

An attempt to print “redtape” fails using the following method as bash attempts print value of “COLORtape” variable.

bash# COLOR=red
bash# echo $COLORtape
bash#

In such cases, braces should be used to protect the bash variable. The following example does that.

bash# COLOR=red
bash# echo ${COLOR}tape
redtape
bash#