Wednesday, April 12, 2006

Shell scripting

What is shell scripting ?

A shell script is a file containing unix/linux commands. Shell scripts are written to avoid repetitive work of issuing the same set of commands over and again. Shell grammar allows us to put conditional and looping constructs (as commands) making it easy to write scripts to do complex tasks.

Following is a simple shell script that shows date, operating system info and list of files in a working directory.

----------------------------
## simple.sh (filename)
echo "a simple shell script"
date
uname -a
ls
----------------------------
Lines starting with a # are comments.

To execute this script,

bash simple.sh
or
sh simple.sh

Shell scripts can be used like any other operating system commands. For this they need to be placed in a directory which the shell searches for commands. You can see these directories by

echo $PATH

You can update the envronment variable PATH to add your own directory to it. Say you want to add ~/bin (directory bin in your home), issue the following commands (bash specific).

PATH=$PATH:$HOME/bin
export PATH

The scripts/programs in this directory need to have execute permission if you want to use them as commands. Execute permission can be added by using chmod command

chmod +x scriptfile

I'll post some examples of small shell scripts in next few posts.

No comments: