Wednesday, September 2, 2020

Bash scripting and shell programming linux part 1

The Part#1 includes:

  • What is a Shell & Types of shells
  • What is Script and how to determine shell
  • She-Bang & comments
  • Steps to create a shell script and execution
  • Variables & usages, assign output command to a variable, Variables Names
  • File and String Test Operators
  • Decision making statements if, if else, if elif else
  • Shell Scripting loops for, while, infinite loop, until

 What is a Shell?

An Operating system is made of many components, but its two prime components are -

  • Kernel
  • Shell

A Kernel is at the nucleus of a computer. It makes the communication between the hardware and software possible. While the Kernel is the innermost part of an operating system, a shell is the outermost one.

A shell in a Linux operating system takes input from you in the form of commands, processes it, and then gives an output. It is the interface through which a user works on the programs, commands, and scripts. A shell is accessed by a terminal which runs it. When you run the terminal, the Shell issues a command prompt (usually $), where you can type your input, which is then executed when you hit the Enter key. The output or the result is thereafter displayed on the terminal.

The Shell wraps around the delicate interior of an Operating system protecting it from accidental damage. Hence the name Shell.

A shell is a command-line interpreter and typical operations performed by shell scripts include file manipulation, program execution, and printing text.

Types of Shell

There are two main shells in Linux:

1. The Bourne Shell: The prompt for this shell is $ and its derivatives are listed below:

  • POSIX shell also is known as sh
  • Korn Shell also knew as sh
  • Bourne Again SHell also knew as bash (most popular)

2. The C shell: The prompt for this shell is %, and its subcategories are:

  • C shell also is known as csh
  • Tops C shell also is known as tcsh

Scripts:

  • contains a series of commands
  • An interpreter executes commands in the scripts
  • anything you can type at the command line, you can put in a script.
  • great for automating tasks.
How to determine Shell:
oracle@test> echo $SHELL
/usr/bin/bash

The $ sign stands for a shell variable, echo will return the text whatever you typed in.

Shell Scripting She-bang:
The sign #! is called she-bang and is written at top of the script. It passes instruction to program /bin/sh.
To run your script in a certain shell (shell should be supported by your system), start your script with #! followed by the shell name.
Example:
#!/bin/bash  
echo Hello World  
  • The first line of a shell script typically starts with a shebang followed by the path to an interpreter that will be used to execute the commands in the script. 
  • If you do not supply a shebang and specify an interpreter on the first line of the script the commands in the script will be executed using your current shell.

Shell Scripting Comments:
Any line starting with a hash (#) becomes comment. Comment means, that line will not take part in script execution. It will not show up in the output.

Steps to create a script and execute:
  • create a .sh file using cat or touch command
  • write the body and saved it
  • provide the execute permission using chmod 777 or chomd +x command
  • execute by ./scriptname.sh
Example:
cat > variable.sh

#!/usr/bin/bash

var1=jai

var2=viru

#Echo

echo "$var1 $var2"

chmod 777 variable.sh

./variable.sh

Output: jai viru

Variables:

  • Storage location that have a name. By convention variables are upper case.
  • Name value pair like variable_name = "Value"
  • Variables are case sensitive

Variable usage:

#! /bin/bash

MY_SHELL="bash"

echo " I like the $MY_SHELL shell"

or 

echo "I like the ${MY_SHELL} shell"

Output:

I like the bash shell

Assign command output to a variable:

#!/bin/bash

SERVER=$(hostname)

echo "The script is running on ${SERVER}"

or 

#!/bin/bash

SERVER=`hostname`

echo "The script is running on ${SERVER}"

Output:

The script is running on LinxTestServer

Variables Names:

  • It contains combination of uppercase and lowercase alphabets, digits and underscore as follows:

FIRST3VARIABLE

FIRST_VARIABLE

FirstVarable

  • Variable names should not start with a digit or not use any special characters other than underscore. For instance,

2FirstVariable

First-Varable

FIRST@VARIABLE

Read-only Variables:

Shell provides a way to mark variables as read-only by using the read-only command. After a variable is marked read-only, its value cannot be changed.

For example, the following script generates an error while trying to change the value of NAME −

 cat > read.sh

#!/usr/bin/bash

NAME="Sri"

readonly NAME

NAME="Rudra"

echo "$NAME"

The above script will generate the following result −

./read.sh: line 4: NAME: readonly variable

Sri

Unsetting Variable:

Unsetting or deleting a variable directs the shell to remove the variable from the list of variables that it tracks. Once you unset a variable, you cannot access the stored value in the variable.

Following is the syntax to unset a defined variable using the unset command −

unset variable_name

The above command unsets the value of a defined variable. Here is a simple example that demonstrates how the command works −

 cat > read1.sh

#!/usr/bin/bash

NAME="Sri"

unset NAME

echo $NAME

The above example does not print anything. You cannot use the unset command to unset variables that are marked readonly. 

 File Operators(Tests):

-d FILE : True if file is a directory

-e FILE : True if file exists

-f FILE : True if file exists and is a regular file

-r FILE : True if the file is readable by you

-s FILE : True if file exists and not empty

-w FILE : True if file is writable by you

-x FILE : True if is executable by you 

String Operators(tests):

-z STRING : True if string is empty

-n STRING : True if string is not empty

String1 = String2 : True if the strings are equal

String1 != String2 : True if the strings are not equal.

Making Decisions:

The if statement:

syntax:

if [ condition is true ]

then 

commands

fi

Example:

#! /bin/bash

MY_SHELL="bash"

if [ $MY_SHELL = "bash" ]

then 

echo "You like the bash shell"

fi


if-else statement:

Syntax:

if [ condition is true ]

then

commands

else

commands

fi

Example:

#! /bin/bash

MY_SHELL="csh"

if [ $MY_SHELL="bash" ]

then

echo " You like bash shell"

else

echo " you dont like bash shell"

fi

if elif else statements:

Syntax:

if [ condition is true ]

then

commands

elif [ condition is true ]

then 

commands

else

commands

fi

Example:

#! /bin/bash

MY_SHELL="bash"

if [ $MY_SHELL="bash" ]

then

echo " You like bash shell"

elif [ $MY_SHELL="csh" ]

then

echo " you like csh shell"

else

echo " you dont like bash or csh shells"

fi

Shell Scripting for loop:

The for loop moves through a specified list of values until the list is exhausted.

Syntax 1:

Syntax of for loop using in and list of values is shown below. This for loop contains a number of variables in the list and will execute for each item in the list. For example, if there are 10 variables in the list, then loop will execute ten times and value will be stored in varname.

for table in {min_value..Max_value..Increment_value}

do

commands

done

Example:

cat >for1.sh

#!/usr/bin/bash

for table in {2..20..2}

do

echo "$table"

done

chmod +x for1.sh

 ./for1.sh

Output:

2

4

6

8

10

12

14

16

18

20

Syntax 2:

for (( initialization;condition;increment/decrement))

do

commands

done

Example:

cat > for2.sh

#!/usr/bin/bash

for (( i=10; i >= 1; i--))

do

echo "$i"

done

chmod +x for2.sh

./for2.sh

Output:

10

9

8

7

6

5

4

3

2

1

Syntax 3:

for Var_name in Item_1 ItemN

do

commands

done

Example:

#! /bin/bash

COLORS="RED GREEN BLUE"

for COLOR in $COLORS

do 

echo "COLOR: $COLOR"

done

Output:

COLOR:RED
COLOR:GREEN
COLOR:BLUE


Scripting while loop:

There is a condition in while. And commands are executed till the condition is valid. Once condition becomes false, loop terminates.

Syntax:

While [ condition ]

Do

commands

done

example:

cat >while.sh

#!/usr/bin/bash

i=10;

while [ $i -ge 0 ] ;

do

echo " reverse order number $i"

let i--;

done

chmod +x while.sh

 ./while.sh

Output: 

reverse order number 10

 reverse order number 9

 reverse order number 8

 reverse order number 7

 reverse order number 6

 reverse order number 5

 reverse order number 4

 reverse order number 3

 reverse order number 2

 reverse order number 1

 reverse order number 0

while infinite loop:

Infinite loop is also called endless loop. It is made with while true (it means condition will always be true) or while : (it means an empty expression), where colon (:) is equivalent to no operation.

 cat whileinfinite.sh

#!/usr/bin/bash

while true

do

echo " this is infinite loop. press ctrl + c to exit"

done

Shell Scripting until loop:

It is similar to while loop. The only difference is that until statement executes its code block while its conditional expression is false, and while statement executes its code block while its conditional expression is true.

Difference between while and until:

Until loop always executes at least once. Loop while executes till it returns a zero value and until loop executes till it returns non-zero value.

Syntax:

Until [ condition ]

Do

Commands

Done

Example:

 cat > until.sh

#!/usr/bin/bash

i=5;

until [ $i -gt 15 ];

do

echo "number $i"

let i++;

done

 chmod +x until.sh

 ./until.sh

Output:

number 5

number 6

number 7

number 8

number 9

number 10

number 11

number 12

number 13

number 14

number 15


Example: Rename all the.jpg files of the current folder to YYYY-MM-DD- filename.
#! /bin/bash
LIST_PICTURES=$(ls *.jpg)
DATE=`date +%F`
for PICTURE in LIST_PICTURES
do
echo "Renaming $PICTURE to $DATE-$PICTURE"
mv $PICTURE $DATE-$PICTURE
done

To continue, go to the next blog page bash-scripting-and-shell-programming-part-2.


No comments:

Post a Comment

Featured Post

11g to 12c OSB projects migration points

1. Export 11g OSB code and import in 12c Jdeveloper. Steps to import OSB project in Jdeveloper:   File⇾Import⇾Service Bus Resources⇾ Se...