Friday 24 April 2015

How to write Bash Script Basic (Shell Script)

Get Started

To automate installations and configurations or routine task, we are required to write scripts to run using bash. Here we will learn how to write simple bash script and make it executable.

What is Bash?

Descended from the Bourne Shell, Bash is a GNU product, the "Bourne Again SHell." It's the standard command line interface on most Linux machines. It excels at interactivity, supporting command line editing, completion, and recall. It also supports configurable prompts - most people realize this, but don't know how much can be done. 

Write your first script

To write a bash script process include,
  • Writing bash script
  • Give it Execution permission to make it executable

Script:

You need to write to any text file, you may use any of your favorite text editor, I will use nano for this post to stop arguments from Emacs or vim(vi). you may use any. shell script is a simple file that contain ASCII text content. Now we will write simple script.
 ~$ nano hello_test.sh

Now put following content in file and save and close (For nano CTRL+O Enter CTRL+X)
 #!/bin/bash
 # My Hello World Script
 echo "Hello World!"

We have written a very simple ever common "Hello World" Program, This script simple printout Hello World! and quit. first line in a script is written to tell shell, which program is used to interpret this script. in this case we are using bash, this path may change if your bash is inst alled in some other location to check your bash path simple type following command.
 ~$ which bash
 /bin/bash

Second line is a comment, every content that is appear after # is skipped by bash. Comments are highly recommended to make your script readable. echo command is used to print in bash.

Give Permission:

Now script is ready, we will give it execution permission. use following command to give script permission.
 ~$ chmod 755 hello_test.sh

Now we can test our script by executing it from shell using following command.
 ~$ ./hello_test.sh

Enjoy.

No comments:

Post a Comment