You too can write Unix/Linux scripts

Are you new to the world of Unix/Linux and hitherto have been impressed by the flexibility of the operating system?
Have you been considering scripting as a very cryptic task reserved for those that earn a living making them?
Well, it's time you hear the truth! Linux scripting is extremely easy and you too can start exploiting the benefits they offer.
Without much ado, let's see an example of a script.

echo "Hello World"

Well that is a full fledged script containing all that is needed in a script, yet it has just two lines.
The first line #!/bin/bash is compulsory in every script and the same across all bash scripts. You might ask what is bash? Bash (Bourne again shell) is the default shell (more like windows command prompt) used in almost all Linux distributions. There are other shells like korn, ash, tcsh and zsh, but lets start with the more common bash shell. So what #!/bin/bash does is to call up the particular shell you want to use (in our case, bash).

The second line echo "Hello World" supplies the called up shell with the command echo. echo is a command that works like print in C or C++, printing specified characters on the terminal's display. In our case, it prints the statement Hello World.

Now to create this script, you can use any text manipulating program you like, but it will be highly advantageous to know how to use vi due to its availability on all Linux distribution.
To create the script using vi, you simply goto the terminal (konsole or command prompt) and after deciding what name to give the script (in this example, I'll use, do the following --
(You will be taken to the vi program screen, press the Insert button on your keyboard to enter the following)
echo "Hello World"
(Now press the Esc button, and type wq to save and exit, press Enter)

Congratulations! You've just created your first script. Now lets run it.
To run the script, you will need to make the file you just created executable, by doing the following
~$chmod +x
Then to run it just do

Below are samples of scripts you can try

# This is a comment and and won't be passed as a command to the shell
# This script displays the date

# This script displays who's logged on and his home directory
echo HOME

The following two examples will require an input data (called parameter)

The scripts will be run like this

$./welcome Michael
$./factorial 10

# This script outputs your name among several other words
echo "Hello $1, you are welcome to my website"

# This script calculate the factorial of any supplied number
for (( number  =  1 ; number <= $1 ; number++ ))
      factorial=$[  $factorial * $number ]
echo "The factorial of $1 is $factorial"

Feel free to ask any question via the comment box.


Post a Comment

Follow me on Twitter | About me | Terms of Service | Privacy Policy