Shortdark Software Development

How to create and run Bash Scripts

Development6th Apr 2019.Last Updated: 28th Oct 2021.Time to read: 2 mins

BashCommand LineCronLinuxUbuntuWP-CLI

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 ~/bin
sudo nano ~/bin/commandname

Then, create the script with the shebang! at the top...

#!/bin/bash
# Update, upgrade, then restart
apt-get -y update
apt-get -y upgrade
apt-get autoremove
service apache2 restart

# update WordPress through WP-CLI
cd /var/www/html
wp core update
wp 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:~/bin
PATH=~/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 exists
if [ -d "$HOME/bin" ] ; then
    PATH="$HOME/bin:$PATH"
fi

Whether, you have added anything new to ".profile" or not, 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

Previous: Interacting with S3 using PHPNext: Creating a Composer Package Tutorial