Shortdark Web Development

How to create and run Bash Scripts

Development 6th Apr 2019. Time to read: 1 min

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...

# 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...


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

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