Bash Programming


Bash is a Unix shell. It is an interface for you to execute commands on different components of the system. Hence it is a command language. It was written by Brian Fox. Bash is a command processor that runs in a text window. The user types commands that cause actions. 

This post gives you the basic knowledge on writing bash scripts on Unix or Linux. Bash scripts are used by any one who uses Unix or Linux system regularly. 

Bash can also read commands from a file called 'script'. Anything you can run normally on the command line can be put into a script and it will do exactly the same thing. You don't need to change anything that you type in command line. Just type the commands as you would normally and they will behave as they would normally. The only difference is that instead of typing them at the command line, the commands that you want to execute are entered sequentially into a plain text file. And that's what bash scripting is!

We normally give an extension of .sh to files that contain bash scripts.


A traditional Hello-World script


#!/bin/bash 
 echo Hello World 


This is a very simple script which executes a command to print the line 'Hello World'. This has two lines.
So what do they really mean? 
The first line indicates the system which program to use to run the file. In this case, the system should use bash to run the script file.
The second line is the only action performed by the script which is to print the 'Hello World' message on the terminal. You can type this command yourself on the command line and it will behave exactly the same.


How do you run the script

Running a bash script is fairly easy. Say you have saved the above file as 'hello.sh'. Type the following command to run the script.

nanduni@nanduni - TECRA-M11:~$ ./hello.sh
In order to execute the script, you must have the execute permission set which is not set by default for safety reasons. Otherwise you will get an error message as below.

nanduni@nanduni - TECRA-M11:~$ ./hello.sh
bash: ./hello.sh: Permission denied
You can set the permission levels in the command line as below.

chmod 755 hello.sh
Then the output of the executed script is as below.

nanduni@nanduni - TECRA-M11:~$ chmod 755 hello.sh
nanduni@nanduni - TECRA-M11:~$ ./hello.sh 
Hello World 
'chmod' means 'change mode'. It is a command and system call which changes the access permissions to file system objects such as files and directories.
Each digit in mode parameter represents permissions for a user or class of users.

                               First digit refers to owner of file.
                               Second digit refers to file's group.
                               Final digit refers to everybody else.

The different permission levels represented by various digits are as follows.

0 : deny all
1 : execute only
2 : write only
3 : execute + write
4 : read only
5 : read + execute
6 : read + write
7 : read + write + execute


0 comments :

Post a Comment