Bash script for beginners

June 25, 2012 in Bash script

Bash scripting for beginners Part 7

Read

Sometimes it’s useful to let the user decide what’s the name of the backup that the script will create. So if you want to give a specific name to the backup you have to let the user type a name. So let’s create a script based on the previous one that will let the user select if he wants to add a specific name for the backup or just let the name with the date and time. To do so let’s create a new script and name it backup6.sh

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

write the following to the gedit :

#!/bin/bash 
# Bash with allaboutlinux.eu
DATETIME="$(date +%d.%m.%Y_%H:%M:%S)"
BKFILE=~/Desktop/bash/backup/backup$DATETIME.tar.gz
BKFOLDER=~/Desktop/bash/code/
BKRESULT=~/Desktop/bash/backup/backup$DATETIME.txt
BKDESTINATION=~/Desktop/bash/backup/
LIST="Backup Quit"
LIST2="Date-Time User-Difine"
select OPT in $LIST; do
if [ $OPT = "Backup" ]; then
echo please chose the filename of the backup:
select OPT in $LIST2; do
if [ $OPT = "Date-Time" ]; then
tar -zcvf $BKFILE $BKFOLDER > $BKRESULT
clear
echo backup saved to:
echo $BKFILE
echo and the results writed to:
echo $BKRESULT
exit
elif [ $OPT = "User-Difine" ]; then
echo "Please specify a name for the backup"
read FILENAME
tar -zcvf $BKDESTINATION$FILENAME.tar.gz $BKFOLDER > $BKDESTINATION$FILENAME.txt
clear
echo backup saved to:
echo $BKDESTINATION$FILENAME.tar.gz
echo and the results writed to:
echo $BKDESTINATION$FILENAME.txt
exit
else
clear
echo bad selection
exit
fi
done
elif [ $OPT = "Quit" ]; then
clear
echo Backup aborded by user
exit
else
clear
echo bad selection
exit
fi
done

 

save and close. Now make the file executable

chmod +x backup6.sh

execute that file with

./backup6.sh

Just a quick explanation of the script:

Here we have added a new variable with the name "LIST2″ in order to create a new "select". You already know that from the previous part of this tutorial.

When we need an input from the user we have to use the "read" command. When this command executed by the script it will wait an input from the user. It’s useful to use an "echo" command before the "read" command in order to give a sort explanation to the user of what the script is waiting from him. You can see that in my script:

echo "Please specify a name for the backup"
read FILENAME

after the "read" you have to type a variable so the read command can store the input of the user. This variable can be used just like normal variables.

Take a close view of the script. I believe that you will not have a problem to understand that script now.

Let’s go to the next part.


Pages: 1 2 3 4 5 6 7 8