This article will show you how to set up a command to run automatically each time you (or any user) log in on the Linux operating system.
Several tasks may be useful to run on login – perhaps you want to connect to a network share or mount a USB drive each time you log in. You might even want to write a script that emails someone to let them know you’ve arrived at work safely and have it sent automatically when you log in. Whatever the reason – here’s how to do it.
Running a Command on Any User Login with /etc/profile
First up, if you want to run a command when any real user logs into the system, you’ll need to edit the following file:
Each line in this text file will be executed when any user logs in, regardless of which Shell they are using.
You can view the current contents of the file by running:
…and edit it using the nano text editor by running:
You’ll need to be logged in as root or have elevated privileges using the sudo command to edit this file.
Running a Command when a Specific User Logs in with ~/.profile
If you only want the commands to run when you log in to your own account, edit the .profile file in your home directory:
Again, each line in this text file is run in the default shell for your user at login allowing you to execute any shell command you wish.
The .profile file is hidden (as it starts with a dot .) – so it won’t show up in direct listings unless you specify that hidden files should be shown:
The above command will list all files as the -a (ALL) option is used.
You can edit your own .profile without any special permissions, but you’ll need root privileges if you want to edit the .profile file in someone else’s home directory.
Things to Watch
Commands in /etc/profile and ~/.profile file will only run when a normal user logs in. Normal users are created to log in and use the system with a shell session and do not include users created for services (for example, the www-data user, which is used by the Apache webserver to run services).
Output is Logged, Not Shown
If the command being run produces any output, it is not shown in the terminal during or after login. Therefore, you will have to inspect the relevant logs to see the program output or ensure that the command’s output is redirected to a location where you can read it from.