In part 1 we looked at how to write a bash script.
We looked at the basics including the importance of shebang, how to clear your screen, take user input and evaluate it.
We also looked at how to use IF, FOR and WHILE loops in your bash script and how you may use these loops with applications or commands.
For our example we looked at how you could use a FOR loop to batch convert wav files to mp3 files.

In this part we are going to look at how you can make your script or simple programs run by themselves at given intervals.
We will also be looking at how to make your bash script look more appealing and easier with a nice GUI using Zenity.
Kdialog is also available for KDE users, but we won’t be covering them here as Zenity is the default for Ubuntu desktops.
For information specific to Kdialog check out http://mostlylinux.wordpress.com/bashscripting/kdialog/ which has great examples of using the different options for all you KDE users.

Let’s begin!

1. Full automation with Cron

Cron is a daemon used by Linux and Unix like systems that allow programs and scripts to be ran at certain times.
The Cron daemon will run constantly to check whether any cronjobs are scheduled and then run them.
This is particularly useful when you need a certain action to be performed at a certain time.
Such actions could be scheduled updates or maintenance for system administrators.
But, they could be anything you desire.

Cron and crontabs are simple to configure and once you understand how they work, you will be ready to go in no time.

Crontabs are the programs used in order to keep cron organised.
There are two types of crontabs, one is for system functions and root privileged actions, the other is for users and does not require root.

The best way to explain crontab and cron is to use it, so let’s use it.

I have a little script which will automate the update and upgrade actions of apt-get. I want this to run at 10 minutes past midnight every day.
The script is located in a directory inside my home directory called scripts/ and the script is called upgrade.sh

To begin, I want to edit my crontab.
I do this by opening a terminal, and typing ‘crontab -e’ without quotes.
Because this is the first time I’m using cron, it will ask me which editor I would like to use.
If you are unsure which to use and you’re a relatively new user, then you want to avoid vim (or vi) and pick nano.
Nano works most like a regular text editor in the terminal, and whilst most people will most likely shout at me for not using vim, I don’t think this is a good time to throw you in the deep end, so go ahead and select nano.

Once selected you will be presented with a file that looks like this:

# Edit this file to introduce tasks to be run by cron.
#
# Each task to run has to be defined through a single line
# indicating with different fields when the task will be run
# and what command to run for the task
#
# To define the time you can provide concrete values for
# minute (m), hour (h), day of month (dom), month (mon),
# and day of week (dow) or use ‘*’ in these fields (for ‘any’).#
# Notice that tasks will be started based on the cron’s system
# daemon’s notion of time and timezones.
#
# Output of the crontab jobs (including errors) is sent through
# email to the user the crontab file belongs to (unless redirected).
#
# For example, you can run a backup of all your user accounts
# at 5 a.m every week with:
# 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/
#
# For more information see the manual pages of crontab(5) and cron(8)

#
# m h dom mon dow command

Wow, this might look like double Dutch to you, so let’s explain what it wants us to do.
First of all, all those lines starting with a hash (#) are comments, so they aren’t read by the system and are for your benefit.

Let me explain the structure of a cron command.
Crontab is divided in two parts. The first is the time for something to be run at, the second is what is to be run.
An example we are provided is:

 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/

Note the first 5 fields before the command ‘tar’: 0 5 * * 1
This tells us when it is to be ran.
They are ordered as follows from left to right:

Minute, Hour, Day of the Month, Month, Day of the Week

By entering a number on any of these places, you are entering a value to that time.
By entering a asterisk (*) on any of these places you are leaving that blank.
So looking at our example, it is is stating that it wants the minutes to be 00, hour to be 05, every day of every month on a Monday to be run.
This is unusual especially since the comments state every day.
Either way, it’s clear this must be run at 5am each day.
Let’s look at how I want my script to be ran.

My script must be ran at 10 minutes past midnight or 00:10 each day.
Therefore the number sequence should be: 10 0 * * *
If I only wanted it to run every 13th day of the month it would be:
10 0 13 * *
Or if I only wanted it ran the 13th of July it would be:
10 0 13 7 *

But let’s stick to my original plan of 10 past midnight each day.
Next would be to tell cron what I want to run, in this case it’s my script upgrade.sh.
This uses absolute pathnames and I also want to tell it to use bash, so I would say:
‘bash /home/me/scripts/upgrade.sh’ (without quotes)

So my crontab should look like this:

10 0 * * * bash /home/me/scripts/upgrade.sh

After that, I am done.
You can add more by placing each individual job on a new line.
Once I’m done, I can save the crontab using Ctrl+O and then Ctrl+X to exit.

Then to list all the jobs type ‘crontab -l’, and to remove a job ‘crontab -r’.
If you want to remove a job for a particular user use ‘crontab -r user’ (replace user with username)

See how simple that is?

2. GUI-dify Bash with Zenity

GUI’s make applications a lot more attractive, and Zenity can do that with bash scripts.
You don’t even need to install another application for it. So if your friend uses Ubuntu or another Linux distribution with Bash and is based on Gnome, then he/she could use the GUI application after you sent it.

Zenity has lots of dialogs it can present to the user, these include (from the GNOME page):
* Calendar Dialog
* Color Selection Dialog
* File Selection Dialog
* Forms Dialog
* List Dialog
* Message Dialog
* Notification Icon
* Password Dialog
* Progress Indicator
* Scale Dialog
* Text Entry Dialog
* Text Information Dialog

We are going to use some examples to create a small little application that has a few of these features.
This is the plan:

We want to create an application with bash that will ask for a password, it will then check if it’s the same as in the script, then if it is, we will ask for a favourite colour.
After that we will ask for a favourite quotation, and finally, we will let bash save them all in a nice little file and place it on the desktop.
If the password was incorrect, we will show a warning dialog box.

So let’s begin by opening Gedit.
First we use the shebang (#!/bin/bash)

Our first zenity dialog should ask for a password, so let’s begin with the following command:

password=`zenity –password`

That’s all that zenity requires for a password.
What happens here is that we created the variable password.
Inside that variable in the sideway quotes (above tab key) we put the command zenity –password.
This tells zenity we want a password dialog.
All the information that is typed in the password dialog then get’s saved in the variable password.

We can now use an IF loop to check whether the password is correct or not.
This is definitely not the way to ask for passwords but it is a good way to show how it works.

We will use the following IF loop:

if [ “$password” == “password123” ]
then
zenity –info –text “Correct!”
else
zenity –error –text “Incorrect Password”
fi

As you can tell by now we first ask to compare the text in variable password, with ‘password123’.
If that is correct, we create an information dialog with zenity’s ‘–info’ argument and use –text to tell what we want to display.
If it is incorrect, we create an error dialog using –error and use –text to display that it is incorrect.

But we want do other things when the password is correct, so let’s remove the info dialog, and start work here.

Now let’s ask for a favourite colour.
Instead of plain and simply asking, why don’t we use a radio list, where a user can pick one.
Let’s begin.

colour=`zenity –list –radiolist –text “Please choose your favourite colour:” –hide-header –column “Choice” –column “Colour” FALSE “Red” FALSE “Blue” FALSE “Green”`

First what we did was create the variable colour.
then in the sideway quotes (is that the right name?) we told zenity we want a form of –list, and we selected the –radiolist, we want the text displayed to be “Please choose your favourite colour:”.
After this we gave –hide-header, that will ensure you don’t see the column names which we also provided. After that we gave the options available, and set them all to FALSE, meaning that none were selected by default.

Since we don’t need to do anything with this, let’s leave it just as it is for now.

Finally we want to ask for a nice quotation, for this all we want is a text entry dialog.
So we could use:

quote=`zenity –entry –text “Enter your favourite quote:”`

What we did here was select –entry for our type of dialog, and provided the text “Enter your favourite quote”, and all this is saved in the ‘quote’ variable.

Now we get to do some bash behind the scenes, and this gives me a chance to show you one more little feature of bash.

What I want to do is make a file with all this information in and place it on the desktop. But considering everyone has a different username, we need to make some small changes.
First we need to create a variable to place the current username in:

user=`whoami`

Whenever you need to put the result of a command in a variable, you need to use sideways quotes.
The whoami command usually displays the current username, but we are going to use it in a moment so we just want the current username inside the variable ‘user.
Next we are going to make another variable to save us time writing out a text file location like this:

outputfile=/home/$user/Desktop/colours_and_quotes.txt

This is more to save time but notice how we use the variable ‘$user’.
Because we saved the current username in that variable, we know it will always be correct.
Please note you would usually just use $HOME, but this was a good excuse to show you how you can really utilize variables.

The chances are, colours_and_quotes.txt does not yet exist on the desktop, and if we want to write anything to it, it will just give us errors saying it doesn’t exist.
Now would be a good time to create it, so our next command is:

touch $outputfile

Touch creates an empty file by whatever name you gave it, here we used the ‘outputfile’ variable to tell touch where we wanted it placed and by what name.
Now we are ready to send our information.

echo “Colours and Quotes” >> $outputfile
echo “—————————–” >> $outputfile
echo “Favourite colour: $colour” >> $outputfile
echo “Quote: $quote” >> $outputfile

The >> simply sends the strings to colours_and_quotes.txt.
A single > will mean it will overwrite whatever was already there, which isn’t handy if we have a few lines to send, but >> will just write one line after the other.
What we also did was use the ‘colour’ and ‘quote’ variables inside the string to be sent over. This will mean that whatever choices were made and quotes were typed in, they will be sent nicely to the text file.

If all went well, you should have a script like this:

#!/bin/bash

password=`zenity –password`

if [ “$password” == “password123” ]
then
colour=`zenity –list –radiolist –text “Please make a selection:” –hide-header –column “Choice” –column “Colour” FALSE “Red” FALSE “Blue” FALSE “Green”`
quote=`zenity –entry –text “Enter your favourite quote:”`

user=`whoami`
outputfile=/home/$user/Desktop/colours_and_quotes.txt
touch $outputfile
echo “Colours and Quotes” > $outputfile
echo “——————————” >> $outputfile
echo “Favourite colour: $colour” >> $outputfile
echo “Quote: $quote” >> $outputfile
else
zenity –error –text “Incorrect Password”

fi

If this renders wrong, please note that I put a tab (8 spaces) worth of white space inside each loop.

If you run this bash script, you will notice that at the end you have a colours_and_quotes.txt file with all the information in.

I’m sure you can find far better uses for Zenity, but I hope that you will have learned something and are able to make creative and interesting scripts.

For more information on Zenity, visit the Gnome site here: https://help.gnome.org/users/zenity/stable/

If you have any interesting and useful applications you want to share, let me know about it.

Advertisements