Spread the love

How to write a Script in Linux

To successfully write a shell script, you have to do three things:

  • Write a script
  • Give the shell permission to execute it

Writing a script

A shell script is a file that contains ASCII text. To create a shell script, you use a text editor. There are many, many text editors available for your Linux system, both for the command line environment and the GUI environment. Here is a list of some common ones:

Command line editors-

  • 1) vi editor
  • 2) vim editor
  • 3) nano editor

GUI editors –

  • 1) gedit
  • 2) kwrite

As I mentioned before, every script file is essentially plain text. That doesn’t mean you can write what you want. When a text file is attempted to be executed, shells will parse through them for clues as to whether they’re scripts or not, and how to handle everything properly. Because of this, there are a few guidelines you need to know.

  1.  Every script should begin with “#!/bin/bash”
  2.  Every new line is a new command
  3.  Comment lines start with a #
  4.  Commands are surrounded by ()

The Hash-Bang Hack

When a shell parses through a text file, the most direct way to identify the file as a script is by making your first line:

#!/bin/bash

If you use another shell, substitute its path here. Comment lines start with hashes (#), but adding the bang (!) and the shell path after it is a sort of hack that will bypass this comment rule and will force the script to execute with the shell that this line points to.

Now , lets start writing a script file –

Go to shell terminal or GUI editor

vim myscript.sh

Write down –

#!/bin/bash
# firmcodes explains script writing

echo "Hello World!"

Note :

  • The second line is a comment. Everything that appears after a “#” symbol is ignored by bash.
  • The last line is the echo command. This command simply prints what it is given on the display.

Setting permissions

chmod +x myscript.sh

Note : Here +x will give it executables permissions. i.e. 0777 (which you might know about permissions in linux).

Now run the scrupt

./myscript.sh

Output : – Hello World!

Contents of Script –

Actually the contents of a script are those commands which we directly put on a shell of linux.

Like cd , ls, sleep , printf , scanf , make , gcc , g++ etc.

Example –

#!/bin/bash

cd <path to dir>

ls

clear

sleep 1         //here 1 means one second

gcc <filename.c>

 

Flow Control in Script

The shell provides several commands that we can use to control the flow of execution in our program. These include:

  • if
  • exit
  • for
  • while
  • until
  • case
  • break
  • continue

About  if

The first command we will look at is if. The if command has three forms:

# First form

if condition ; then

commands

fi

 

# Second form

if condition ; then

commands

else

commands

fi

 

# Third form

if condition ; then

commands

elif condition ; then

commands

fi

EXAMPLE :

This example illustrates use of if else statement in script.

#!/bin/bash

echo -n "Type Password ! > " 
read  text; 

echo "You entered: $text" 
        if [ "$text" = "firmcode" ];then 
                echo "Login to Firmcode Success"      
        else 
                echo "Sorry" 
        fi

NOTE : –

read

To get input from the keyboard, you use the read command. The read command takes input from the keyboard and assigns it to a variable.

Use of Case condition –

case selectively executes statements if word matches a pattern. You can have any number of patterns and statements. Patterns can be literal text or wildcards. You can have multiple patterns separated by the “|” character. Here is a more advanced example to show what I mean:

#!/bin/bash

echo -n "Type a digit or a letter > "
read character
case $character in

    	[a-z] | [A-Z] ) echo "You typed the letter $character"
            ;;

    [0-9] )     echo "You typed the digit $character"
            ;;

            # Check for anything else
    * )         echo "You did not type a letter or a digit"
esac

Output –

Type a digit or a letter > q

You typed the letter q

Type a digit or a letter > 1

You typed the digit 1

Type a digit or a letter > @

You did not type a letter or a digit

Note –

Here *) – means default case when we are using in c language.

When you type a-z or A-Z it will goto that case and show the statement. Similarly for digit case.

In echo statement -n means remain in same line to take input.

Writing a function in script –

Simply start writing script –

#!/bin/bash 
foo() 			//function definition
{ 
        echo "Test Function" 
} 

foo 		// calling of function foo

Output :-

Test Function

-> Here function is just called by simply type the name of function.

Passing a argument to a function –

#!/bin/bash

Timecount() 				//function to count time
{ 
        min = $1 				//argument 1
        sec  = $2 				//argument 2
        while [ $min -ge 0 ]; do 		//while condition
                while [ $sec -ge 0 ]; do 
                        echo -ne "00:0$min:$sec\033[0K\r" 
                        sec=$((sec-1)) 
                        sleep 1 			//sleep call of 1 second.
                done 
                sec=59 
                min=$((min-1)) 
        done 
} 

Timecount 0 8			//calling of a function and pass 1st argument as 0 and 2nd argument as 8

Output : –

00:00:8

it will decrease to 00:00:0 and then exit.

Pass command line arguments to script.

Start writing a script –

vim myscript.sh
#!/bin/bash
###########    Main Code Start From Here    ###########
case "$1" in 

        ''1") 
	
	echo ''You provide : $1 argument''
               

        ;; 

      *) 

                echo ''No argument provided'' 

        ;;
esac

Output:-

Run – ./myscript.sh 1 //here 1 is passong as a argument.

You provide : 1 argument

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~