Linux: Run a Bash Script Only Once at Startup

PowerADM.com / Linux / Linux: Run a Bash Script Only Once at Startup

In this article, we will look at how to run a bash script only on the first user login to Linux (or only on the first boot).

On Linux, you can run scripts at user login via these files:

  • ~/.bash_profile
  • ~/.bash_login
  • ~/.profile
  • /etc/profile.d

If you want to run the bash script for a specific user only, you need to specify the bash script files in their profile (~/.profile). If you want to run the script for all users, you must place it in the /etc/profile.d directory.

Here is an example bash script that creates a .logon_script_done file in the user’s profile when executed. The next time the script is run, it checks if this file exists, and if it does, the bash script code stops running.

#!/bin/bash
if [ -e $HOME/.logon_script_done ]
then
 echo "No actions to do"
else
 echo "First run of the script. Performing some actions" >> $HOME/run-once.txt
 touch $HOME/.logon_script_done
fi

Save the code to the file user_provision.sh and allow the file to be run:

$ chmod +x user_provision.sh

Now you need to add a path to the script at the end of the .profile file:

. ${HOME}/user_provision.sh

Run a custom bash script, only once, at boot time on LInux

Log out (exit) and log in again. A run-once.txt file will be created in the user profile.
check flag file on linux

The code from the bash script will not run the next time the user logs in.

Leave a Reply

Your email address will not be published. Required fields are marked *