Bash scripts are great for automating tasks that might otherwise take several minutes. If a series of tasks doesn’t require any feedback, it just requires the commands to be entered in order, a bash script is perfect. One can set the script up and run it in the morning, then make a coffee while it goes through the different stages. If anything bad happens during the execution, you’ll see plenty of red on your return to the computer.
This example stores a series of commands to update the ubuntu operating system, restart the Apache web server and update the WordPress core. This command can be run manually by the user, or can be set up to run automatically with cron. The reason to not run the updates automatically would be in case something breaks, if you don’t witness the break your website(s) may be down until you realise they’re not working.
While I found the updating script useful and time-saving for a while, some better uses of a bash script might be…
This article is from 2019, introduction written in 2024…
To create a bash script that will work only for your user, you can store the bash files in your user’s home directory. The standard place to put them would be a folder called bin. Create it if it does not exist, then create the file. The name of the file is the name of the command you want to type to run it. So, if I want to call my command “commandname”, I would do…
mkdir ~/binsudo nano ~/bin/commandname
Then, create the script with the shebang! at the top…
#!/bin/bash# Update, upgrade, then restartapt-get -y updateapt-get -y upgradeapt-get autoremoveservice apache2 restart# update WordPress through WP-CLIcd /var/www/htmlwp core updatewp plugin update --all
Now, make the file executable…
sudo chmod +x ~/bin/commandname
Then, to run the file from any directory, you’ll have to update your user’s .profile file…
sudo nano ~/.profile
Adding the following to ~/.profile tells linux that there are executable scripts in the ~/bin directory…
PATH=$PATH:~/binPATH=~/bin:$PATH
There may also be something like this already in the “.profile” file, in which case you do not need to add anything extra…
# set PATH so it includes user's private bin if it existsif [ -d "$HOME/bin" ] ; thenPATH="$HOME/bin:$PATH"fi
If you have added anything new to “.profile” you’ll need to reload “.profile” by running…
. ~/.profile
Now you should be able to run the command, commandname, from any directory.
You can run this manually from the command line or you can create a cron to run it at regular intervals.
1 * * * * /bin/bash -c "~/bin/commandname"
Then reload the cron with…
sudo service cron reload
You can monitor the cron log in real-time with tail…
tail -f /var/log/syslog
Or, something like this to get the history for today…
cat /var/log/syslog | grep CRON
Quick Links
Legal Stuff