Swiftorial Logo
Home
Swift Lessons
Tutorials
Learn More
Career
Resources

Handling Signals in Shell Scripts

This tutorial provides a detailed explanation of handling signals in shell scripts, including how to catch, ignore, and send signals to processes.

1. Understanding Signals

Signals are a form of inter-process communication used to notify a process that a specific event has occurred. Signals can be sent by the operating system, other processes, or even by the process itself. Common signals include SIGINT (interrupt), SIGTERM (termination), and SIGHUP (hang up).

2. Common Signals

  • SIGINT (2): Interrupt signal, usually sent when a user presses Ctrl+C.
  • SIGTERM (15): Termination signal, used to request a process to stop.
  • SIGHUP (1): Hangup signal, sent when a terminal disconnects.
  • SIGKILL (9): Kill signal, forces a process to terminate immediately.
  • SIGSTOP (19): Stop signal, pauses a process.

3. Catching Signals

You can catch signals in a shell script using the trap command. The trap command allows you to specify a command to run when a signal is received. For example, to catch the SIGINT signal and run a cleanup function:

#!/bin/bash

cleanup() {
  echo "Cleaning up...";
  exit 1;
}

trap cleanup SIGINT

echo "Press Ctrl+C to trigger the trap."
while : ; do
  sleep 1;
done

In this example, when the user presses Ctrl+C, the cleanup function is called, and the script exits gracefully.

4. Ignoring Signals

You can ignore a signal by using the trap command with an empty string. For example, to ignore the SIGINT signal:

#!/bin/bash

trap "" SIGINT

echo "Press Ctrl+C, but it will be ignored."
while : ; do
  sleep 1;
done

5. Sending Signals

You can send signals to a process using the kill command. By default, kill sends the SIGTERM signal. To send a different signal, use the -s option followed by the signal name. For example, to send a SIGINT signal to a process with PID 1234:

kill -s SIGINT 1234

You can also use the signal number:

kill -2 1234

6. Example Script

Here is an example script that demonstrates handling signals:

#!/bin/bash

cleanup() {
  echo "Cleaning up...";
  exit 0;
}

trap cleanup SIGINT SIGTERM

echo "Script is running. Press Ctrl+C to stop."
while : ; do
  echo "Running...";
  sleep 2;
done

In this script, both SIGINT and SIGTERM signals are caught, triggering the cleanup function to execute and terminate the script gracefully.

7. Conclusion

In this tutorial, you learned how to handle signals in shell scripts. This includes catching, ignoring, and sending signals. By effectively managing signals, you can create more robust and reliable shell scripts that can handle unexpected interruptions gracefully.