I want to run a command, say touch ~/test.txt every time I'm logging out from my computer. Is that possible, and if so how should I go about doing this? I've looked at other responses but they were a bit too obscure. Specifically one mentioned that I should be finding some sort of 'common' file if I want this command to run for all user logout events. Any help is welcome, thanks ahead of time.
2 Answers
If you mean "logging out" as closing GUI session..
Depends what GUI you use:
Gnome: The script /etc/gdm/PostSession/Default
is run by root whenever someone quits his X session.
Source: How can I make a script run automatically after gdm login and logout? | Ask Ubuntu
Unity (Ubuntu default): in /etc/lightdm/lightdm.conf
.
below a chapter of [SeatDefaults]
a command session-cleanup-script=/path/to/your-script.sh
will do the trick.
Source: How to run a script at logout | Ask Ubuntu
KDE will run /usr/shutdown
script.

- 316
- 2
- 8
If you aren't talking about the GUI, it depends on your shell:
bash has a ~/.bash_logout file that gets executed when a login shell closes.
zsh has a .zlogout (in your home or in the $ZDOTDIR directory).
You can put pretty much anything in either and have it run when you log out.

- 176
-
So I tried running a random touch logout command, didnt work. Any thoughts? – Darpan Ganatra Oct 19 '17 at 17:16
-
I have a .zlogin file that just runs "fortune" and a .zlogout with: "touch ~/logout_time" -- not sure about the bash version, but make sure you are running a login shell (see here: https://unix.stackexchange.com/questions/38175/difference-between-login-shell-and-non-login-shell). GL! – docwebhead Oct 23 '17 at 14:23
Before
target (haven't checked). If it is, you'll want to write a systemd unit which executes your command . – bytefire Oct 18 '17 at 15:36systemctl list-unit-files -t target
to get a list of all targets but without knowing off the top of the head, one would need to lookup likely candidates. – bytefire Oct 18 '17 at 16:14