Bash script for beginners

June 25, 2012 in Bash script

Bash scripting for beginners Part 4

Variables

In this part we will not make an improvement of backup2.sh but we will use some variables to make our life easier. Variables will also make scripts shorter and easier to read. Maybe you will disagree with that at the begining but you will totally agree when you will make large and complicated scripts. To do so let’s create a new script and name it backup3.sh

gedit ~/Desktop/bash/code/backup3.sh

write the following to the gedit :

#!/bin/bash  
# Bash with allaboutlinux.eu
BKFILE=~/Desktop/bash/backup/backup.tar.gz # the desination and the filename of the compress backup folder
BKFOLDER=~/Desktop/bash/code/ #the folder that we want to backup
BKRESULT=~/Desktop/bash/backup/backup.txt # the destination and filename of the log file
tar -zcvf $BKFILE $BKFOLDER > $BKRESULT
echo backup saved to $BKFILE and the results written to $BKRESULT

save and close. Now make the file executable

chmod +x backup3.sh

execute that file with

./backup3.sh

Just a quick explanation of the script:

This is really self explained script so I will write a few words about variables. In order to create a variable you need a name followed by "=" and then the content of that variable. It is that simple. So you can create a string variable named "strvar" that will contain "Bash script for beginners" like that:

strvar="Bash script for beginners"

Or you can create a numeric integer variable named "intvar" that will contain the number "10″ like that

intvar=10

We will use more variables in the next part so you will understand that better.

In order to use a variable just put "$" in front of the name.

So if you use the "echo" command that you learned earlier followed by a variable, echo will print in the terminal the containing data of that variable. For example:

echo $strvar

it will print:

Bash script for beginners

but if you use:

echo strvar

it will print:

strvar

I hope that’s enough for variables. Let’s move on, to the next part.


Pages: 1 2 3 4 5 6 7 8