October 4, 2015

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.


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


And now, the script itself:

## 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 ]
echo "The backup directory exists."
echo "A backup directory does not exist, and will be created."
mkdir $HOME/1backups
echo "A backup directory has been created"

# now we define our own variables
# location of files to backup
# name of compressed archive
# location of backup directory
# create compressed archive, copy to backup directory

echo "Jolly good show, the backup worked!"
echo "Dagnabit, the backup failed. Time to debug."

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

Sitemap | Contact Us