Bash script for beginners

June 25, 2012 in Bash script

Bash scripting for beginners Part 3

stdout to file

Let’s make some improvements to the previous script. In this part I will explain to you how to keep a log file of the backup files into a text document. To do so let’s create a new script and name it backup2.sh

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

write the following to the gedit :

#!/bin/bash  
# Bash with allaboutlinux.eu
tar -zcvf ~/Desktop/bash/backup/backup.tar.gz ~/Desktop/bash/code/ > ~/Desktop/bash/backup/backup.txt
echo "backup saved to ~/Desktop/bash/backup/backup.tar.gz and the results written to ~/Desktop/bash/backup/backup.txt"

save and close. Now make the file executable

chmod +x backup2.sh

execute that file with

./backup2.sh

Just a quick explanation of the script:

What we added here is the “> ~/Desktop/bash/backup/backup.txt” at the end of the second line. This will store the output of that command to a file with the name backup.txt

You can add “>” at the end of a command and then a filename.txt to write in that file the output of a command. For example:

ls > ls.txt

The “ls” command normally will print in the terminal the files and directories that are in the current directory. But instead of that the command:

ls > ls.txt

will print the same data in a text file with the name ls.txt.

In the third line I have just added some more information to print in the terminal before that script ends.

So now you have an improved backup program and also you know how to use stdout to file.

Let’s proceed to the next part.


Pages: 1 2 3 4 5 6 7 8