Friday, October 9, 2009

Linux - Bash Shell Scripting - An Example

A script file can contain regular Bash commands, e.g., rm, cp, mv, ls, etc. A script file can also define variables and assign them values. As we will see shortly, the Bash shell programming language is quite sophisticated and allows if statements, loops, and procedures. Here is a sample shell script which moves to directory tmp and deletes all of the .o files (the script file is named rmo.sh),

#!/bin/bash
# usage: rmo
mv tmp
rm *.o
$ ./rmo.sh
./rmo.sh: Permission denied

The shell script failed to run because shell scripts are not executable files by default. To make the shell script file executable, you must change the permissions using the chmod command to add x,

$ ls -l rmo.sh
-rw-r--r-- 1 jdoe jdoe 122 Oct 17 11:35 rmo.sh
$ chmod 744 rmo.sh
$ ls -l rmo.sh
-rwxr--r-- 1 jdoe jdoe 122 Oct 17 11:35 rmo.sh
$ ./rmo.sh

A slightly more sophisticated program might use variables,

#!/bin/bash
# usage: rmo
dirname=tmp
pattern=*.o
cd $dirname
rm $pattern

Here dirname and pattern are variables. Note that when the variable is assigned to (using =), we do not put a $ in front of the variable name, but we do use a $ when referring to the variable later on. If you don't, the shell will think that the variable name is the filename of a program to be executed and it will probably fail with an error message.

Previous - Arithmetic and Relational Operators | Next - Command Line Arguments

No comments:

Post a Comment