Saturday, November 19, 2011

Shell Scripting 2 - What is Shell Scripting ?

In my previous post I've explained what Linux Shell is. Simply it is another program where you can give commands in text mode to get some work done.

However you can write a sequence of commands in a file and tell the shell to execute those commands. Then those files are called shell scripts. (File extension is .sh)

Such a script can be defined as a specific command defined to get a specific work done.

Shell scripting is very useful in a way that, if you want to do a task again and again then you can write the required commands as a shell script and execute it.

Ok, now let's try a simple shell script.

A Simple Shell Script

BASH is the default shell for Linux. Let's script using BASH commands. First we will write a simple script to print "Hello world ! " in the terminal.


You can use any text editor (gedit, vi, emacs, etc.) to write a shell script. Remember the script should be saved with .sh extension. 

Write the following lines in a file and save it as 'hello.sh'.
#!/bin/bash
echo "Hello, World!" 
Now you can execute this hello.sh script.
  1. Open a terminal
  2. Go to the location where you've saved the above file
  3. Then to execute, type, sh hello.sh (Or else you can give execution permission to the above file and then execute it.)
If you have a little touch with shell commands you know the above line no. 2 is enough for printing "Hello, World" in the terminal. So why do we include line no.1 's content ?

It is called a shebang or a "bang" line. In this line we give the absolute path to the BASH interpreter.

Shebang includes the hash sign and an exclamation point character (#!), followed by the full path to the interpreter such as /bin/bash. This will ensure that, the script is using the specified BASH interpreter even if it is executed under another shell.

Note : Giving execution permission to the script.

To give the execution permission to the file you can use the following command.

>> chmod  +x  /path to file

This is a very simple shell script. We can do a lot of things using shell scripting. Hope to bring them one by one in my next posts.