Have a Bash With This Linux Shell - page 3
This script demonstrates a number of common ways to use Bash. A slick Bash trick is to take a script like this, and execute it one line at a time. That's a great way to build and test a script.
To run it as a script, save it as text file, with a nice name like "backup," and make it executable:
chmod +x backup
There are severals ways to run it. Change to the directory it's in, and use one of these:
$ ./backup $ bash backup
Or, do what leet geeks do, and put it in /usr/bin. Or keep it all to yourself- create your own personal scripts directory, and put it in your path:
Append to your PATH, using your own filepath, of course.
This allows you to run the script like any other command:
And now, the script itself:
#!/bin/bash ## This is the famous "sha-bang" statement, ## that tells the shell which command ## interpreter to use. See man magic ## to learn the inner workings of sha-bang. ## this script uses the tar, mkdir, and cp commands ## plus Bash's conditional statements ## smart admins write lots of comments # test for existing backup directory # if it does not exist, create it # -e is the Bash way of asking "does this file exist" # $ means variable substitution. HOME is a builtin # Bash variable. if [ -e $HOME/1backups ] then echo "The backup directory exists." else echo "A backup directory does not exist, and will be created." mkdir $HOME/1backups echo "A backup directory has been created" fi # now we define our own variables # location of files to backup FILES=$HOME/archive-files # name of compressed archive ARCHIVENAME=backups.tgz # location of backup directory BACKUPDIR=/archive/carla/ # create compressed archive, copy to backup directory tar czf $ARCHIVENAME $FILES cp -ap $ARCHIVENAME $BACKUPDIR if [ -e $BACKUPDIR/$ARCHIVENAME ] then echo "Jolly good show, the backup worked!" else echo "Dagnabit, the backup failed. Time to debug." fi
Going through this script and understanding which parts are Bash commands, and which are Linux commands, is important for understanding how to put scripts together.
Bash home page
"Learning the Bash Shell," by Cameron Newham, Bill Rosenblatt
"Linux In A Nutshell," by Ellen Sievers
[This article originally appeared on CrossNodes, a fellow JupiterWeb site. -ed.]
Solid state disks (SSDs) made a splash in consumer technology, and now the technology has its eyes on the enterprise storage market. Download this eBook to see what SSDs can do for your infrastructure and review the pros and cons of this potentially game-changing storage technology.
- 1Linux Top 3: CoreOS, Oracle Enterprise Linux 7 and Ubuntu 14.10
- 2Linux Top 3: Debian Dumps SPARC, Ubuntu Takes Over Linux 3.13 and the Core Infrastructure Initiative
- 3Linux Top 3: Fedora, Ubuntu and Gluster Lose Community Leaders
- 4Red Hat Enterprise Linux 7 Finally Hits the Big Time
- 5Linux Top 3: Tails 1.0, OpenMandriva Lx 2014.0 and Debian 7.5