Amazon

Dec 16, 2009

Linux howTo: shell sccripting part 1

In this post we will walk through the different parts of shell scripting. It is intended for beginners and those folks who want a refresher. We will use any text editor you like ('vi' is also ok).

Difficulty: Basic

So let's start. Open your favorite editor. Copy and paste the following code block(red font).

#! /bin/sh
# my first script


echo "Hello World"

exit 0


Save it as scriptpart1.sh, we use the .sh file extension so that we know that this file is a shell script. After saving the file. We need to make the file executable.
At the command line type the following and press enter

user@penguin$ chmod 755 scriptpart1.sh

You can now execute the script.

user@penguin$ ./scriptpart1.sh
Hello World
user@penguin$

You should see the Hello World at the command line after you press enter.

Let's start understanding every line of the script

#! /bin/sh

Is the entry point of the script. #! is also known as shebang while /bin/sh is the interpreter. It will use the /bin/sh environment.

/bin/sh is known as Bourne shell.
/bin/csh is known as C shell.
/bin/bash is known as Bourne-again shell.

There are lots of unix shell but our main focus is the Bourne shell.

How to know the complete path of the interpreter we are using?

Answer: At the command line type 'which sh' and press enter
user@penguin$ which sh
/bin/sh
user@penguin$

In this machine that I'm using, the sh path is at /bin/sh. We can now move on to the next line which is:

# my first script

This line is a comment one. You can actually put some notes in the script. Note that #! is not a comment. Comment is very useful, you can put anywhere in your code. Standard practice is to put a short and precise comment.

Next part is the blank line. Shell script will ignore the blank line and it will go to the next line. Next line is the echo line.

echo "Hello World"

echo in Linux means displaying the word in the command line. That's why we have 'Hello World' displayed after we ran the script.

We are almost done. You can now display messages using the echo command.

Last part is the exit.

exit 0

It will exit the script. And the number 0, it will tell to the Linux current process that the script exited at 0, meaning successful. We will elaborate next time regarding the exit code of commands and script.

So that's how we write a script. Till next time. Feel free to comment on this post.

No comments:

Post a Comment