October 24, 2014
 
 
RSSRSS feed

Have a Bash With This Linux Shell - page 3

Bashing About

  • February 19, 2004
  • By Carla Schroder

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:

mkdir ~/scripts

Append to your PATH, using your own filepath, of course.

/home/carla/scripts

This allows you to run the script like any other command:

backup

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.

Resources
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.]

Sitemap | Contact Us