Thursday, March 28, 2013

Shell Scripting 01: Hello World


Hi readers. It has been long since my last post here. For the past one and a half year I was bit lazy in writing up what I have learned. Now I think its time to become live on blogger.

For the past one week I was thinking of what to post. For the past 2 years I have done many experiments ranging from micro controllers to Linux and recently getting into power electronics. But among these, one which I felt very powerful was shell scripting. For me it felt like giving me enormous power and control over my system without putting much effort. So I decided to start a small series on shell scripting in Linux.

For this entire series I will be using Ubuntu 12.04 LTS desktop edition for testing the scripts posted here. Even though the distribution isn't a big deal quite often, at times the knowledge of distribution can cost a lot. You cannot expect a detailed explanation of shell scripting here. Rather, I will be posting here shell scripts, so that you can catch up, how the stuff works.

So lets dive in. Open up your shell (sh or bash). Using your favorite text editor type in the following and save to create your first Hello World script.

#!/bin/sh
# This script prints Hello World.
echo "Hello World"
exit 0


Get back to the terminal. Enter the following command to make the script file you created above executable.

$:chmod +x filename

Now run the script by entering 

$:./filename 

Cheers....

You have your first script running.

How it works

Scripts are basically collection of shell commands. Almost all the commands used in shell can be used in shell scripts also. Shell scripts are means to automate our routine tasks.

Now lets examine the above script. The very first line ' #!/bin/sh ' tells the system, the shell to be used to execute the following script. In Linux its common to use sh or bash shell. 

In shell scripts lines beginning with a ' # ' denotes comments and are not executed.
 
Third line ' echo "Hello World"  ' is the actual command. Echo command prints whatever given to it as parameter.

Finally last line is the exit command which ensures  a return from the script. It is good to return some sensible values, so that these can be used for conditional checks in other scripts.

Now that you have written your script in a file. But a file by default is not executable. chmod +x command is used to make a file executable. Once you make the script file executable you can run the script by typing the script file name.

Thats all for now. In the next post we will be talking about using variables in scripts.



0 comments:

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More

 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | coupon codes