Linux / UNIX: Run Commands When You Log Out

Linux / UNIX: Run Commands When You Log Out

To run commands when you log out of a Linux or Unix system, you can use the trap command in a shell script.

The trap command allows you to specify a command or series of commands to be executed when a specified signal is received. You can use the trap command to run commands when you log out of the system by specifying the EXIT signal.

Here is an example of how to use the trap command to run commands when you log out of the system:

  1. Create a shell script with the commands you want to execute when you log out of the system:
#!/bin/bash

# Commands to be executed when you log out of the system
echo "Goodbye!"
Sou‮w:ecr‬ww.lautturi.com
  1. Use the trap command to specify the EXIT signal and the name of the shell script:
trap "/path/to/script.sh" EXIT

Replace /path/to/script.sh with the path to the shell script you created in step 1.

  1. Save the file and make it executable:
chmod +x /path/to/script.sh

This will make the shell script executable.

  1. Add the trap command to your ~/.bashrc file:
echo "trap '/path/to/script.sh' EXIT" >> ~/.bashrc

This will add the trap command to your ~/.bashrc file, which is executed whenever you start a new Bash shell.

Now, whenever you log out of the system, the commands in the shell script will be executed before the system logs you out.

You can use the trap command to run any command or series of commands when you log out of the system. For example, you can use it to save the state of your terminal session, clean up temporary files, or perform any other tasks you need to do before logging out.

Keep in mind that the trap command is a powerful tool that can be used to execute commands when a specified signal is received. You should use it with caution to avoid unintended consequences.

Created Time:2017-10-29 22:08:57  Author:lautturi