Showing posts with label Linux Shell Scripting. Show all posts
Showing posts with label Linux Shell Scripting. Show all posts

Thursday, 8 August 2019

SHELL SCRIPT: HOW TO ADD MULTIPLE SEQUENCE NUMBERS

This can be acheived in many ways.
Through for loop
Write a for loop using {}(know more about {} HERE) to mention the range of numbers and use let command to add those numbers. Below is the script which will uses for loop to add 1 to 100 numbers
#!/bin/bash

j=0
for i in {1..100}
do
let j=j+i
done
printf “Sum of 1 to 100 numbers is %d” $j
Explination: for will take each number in to i variable and adds up to j for each loop and give you the final result in j as shown in above printf command.
Note: Try to avoid echo command as much as possible as this is not protable.
Through while loop: Loop will continue while the condition is true.   #!/bin/bash 
j=0
i=0
while [[ "$i” -le 100 ]]
do
let j=j+i,i++
done
printf “Sum of 1 to 100 numbers is %d” $j
Explination: While loop will check for condition that i less than equal to 100, the loop passes untill i reaches 100. let command is used to increment j and i. And then final value is stored in j. 
Through untill loop: Untill loop is similar to while loop but in reverse. Loop will happen untill the condition is true.
#!/bin/bash

j=0
i=0
until [[[[ "$i” -gt 100 ]/strong>
do
let j=j+i,i++
done
printf “Sum of 1 to 100 numbers is %d” $j
Through awk scripting. 
seq 1 100 | awk ‘{ sum+=$1} END {print sum}’
Hope this helps to add multiple numbers for a given range.

Monday, 5 August 2019

Linux - Simple View of Functions in Shell Script with some practical examples

Shell programming provides the feature of functions  just like any other programming  language. This help us develop the program in a modular manner.Using functions in shell script to perform repetitive tasks is an excellent way to create code reuse. Code reuse is an important part of modern object-oriented programming principles.

What are functions in Shell Script?
Functions are  group pieces of code in a more logical way or practice the divine art of recursion.
Why do require functions?
  1. It helps us reuse the  code
  2. Improve readability
  3. Make debugging easier
  4. Display program as a bunch of steps
How to declare the function ?
Declaring a function is just a matter of writing function

exampl_func  ()
{
Code..
}.
How to call the functions in shell script?
Calling a function is just like calling another program, you just write its name.
exampl_func
Different type of Functions in shell script
Function with out parameter
 
#!/bin/ksh
Hello ()
{
Echo “hello how are you”
}
hello
exit 0
Function with parameter passing
 
Count and display the number of files in the specified directory.
#!/bin/ksh
FILECOUNT ()
{
CDIR=$1
Fcount=`ls -l $CDIR | wc –l`
printf “There are $Fcount files in $CDIR. \n”
}
FCOUNT /export/home/
exit 0
Function with return parameter

#!/bin/sh

# Define your function here
Hello () {
echo “How are you $1 $2”
return “success”
}

# Invoke your function
Hello Tom Hanks

# Capture value returned by last command
ret=$?
Some useful examples of functions in shell script
Setting the oracle environment
set_Ora_Env ()
{
ORAENV_ASK=NO; export ORAENV_ASK
export ORACLE_SID=$1
. /usr/local/bin/oraenv
}
Checking the OS username
Check_OS_Username ()
{
USER=`id|awk -F'(‘ ‘{print $2}’|awk -F’)’ ‘{print $1}’`
case ${USER} in
$1)
: ;;
*)
echo
echo “$PROG: Must be run as user $1”
echo “Usage: $PROG <SID>”
exit 1;;
esac
}
Checking the number of arguments passed in the scripts
Check_Options ()
{
if [ $# -ne 1 ]
then
echo “\n$PROG: Incorrect number of arguments”
echo “Usage: $PROG <SID>”
echo “$PROG: Abort: exit status 1\n”
exit 1
fi
}

Writing loop statement in Unix/Linux shell scripting with examples

What is loop statement in Unix shell scripting

A group of instruction that is executed repeatedly until a termination condition is met is called a loop.
Bash supports for and while loops. Some shell supports until also
How it works
In each and every loop, The variable used in loop condition must be initialized, then execution of the loop begins.
A test (condition) is made at the beginning of each iteration. The body of loop ends with a statement that modifies the value of the test (condition) variable. Loop is executed till the time, the test condition remain valid.
All the loops have a limited life and they come out once the condition is false or true depending on the loop.
A loop may continue forever due to required condition is not met. A loop that executes forever without terminating executes an infinite number of times. For this reason, such loops are called infinite loops
Lets take a look at different loop syntax
For Loop Unix shell
Syntax
The for statement
for command-list1
do
command-list2
done
Let start with one unix shell script for loop example
username=“Jat bob Thor Neil”
for uname in $username
do
echo “Username is $uname”
done
  1. do and done are reserved words
2. do and done must be preceded by a newline or ; (semicolon).
3 . Small loops can be written on a single line. For example:   for var in list; do commands; done
More unix shell script for loop example
To go through each file in the current directory and mention the filetype of each file
#!/bin/sh
for i in *
do
echo $i
file $i
done
While Loop
Syntax
The while statement
while command-list1
do
command-list2
done
Example
x=20
while [ $x >= 10 ]
do
echo “$x”
echo “\n”
sleep 5
x = x – 1
done

20
19
18
17
16
15
14
13
12
11
More examples
i=0
while [ $i -lt 5 ]
do
echo My id is $i
i=`expr $i + 1`
done
Until loop
Syntax
The until statement
until command-list1
do
command-list2
done
Example
until test -f $file
do
sleep 60
done
echo “$file now exists”
Nesting of Loops
We can do nesting of loops also
while test condition ; # this is loop1, the outer loop
do
Statement(s) to be executed if first test condition  is true
while test condition  ; # this is loop2, the inner loop
do
Statement(s) to be executed if test condition 2 is true
done
done

The break and continue statements in loops
It is often necessary to handle exception conditions within loops. The statements break and continue are used for this.
BreakContinue
It is often necessary to handle exception conditions within loops. The statements break and continue are used for this.
The break command terminates the execution of the innermost enclosing loop, causing execution to resume after the nearest done statement.
To exit from n levels, use the command:
break n
This will cause execution to resume after the done n levels up.
The continue command causes execution to resume at the while, until or for statement which begins the loop containing the continue command
Examples for Continue
for filename in `cat filename.txt`
do
if [ ! -f $filenname ] ; then
continue
fi
echo “Found file $filename”
done
Examples for break
for filename in `cat filename.txt`
do
if [ ! -r $filename ] ; then
echo “Cannot read $filename, quitting loop”
break
fi
echo “Found file or directory $filename”
done

Learn unix shell scripting: The Basics

We have already written about Unix Shell scripting ,What is its uses, what are various type of shells and what are positional parameters

In this post, I will  write about unix shell scripting basics and creating first shell scripts for the beginners and how to learn unix shell scripting




First of all unix shell scripting basics
Scripts must contain complete documentation
Each script must contain internal comments that document
The name of the script
The purpose for the script
The name of the author(s)
The date the script was written
The date(s) the script was modified.
The name of each script must reflect its use
Each script must have a suffix that describes the script, for example “.sh” for Bourne shell scripts, “.ksh” for Korn shell or “.cgi” for Common Gateway Interface scripts.
Lets create the first shell script
#!/bin/ksh
# This script displays the date, time, username and
# current directory.
echo “Current date and time is:”
date
echo
echo “Your username is: `whoami` \\n”
echo “Your current directory is: \\c”
pwd
echo “Your system name is :`hostname`\\n”


Explanation of each line in the scripts is given below
  1. #!/bin/ksh as the first line of the script .It is used to tell the script to execute with ksh shell
2. The second two lines beginning with a hash (#) are comments and are not interpreted by the shell.
3.Use comments to document your shell script.
4. The backquotes (`) around the command whoami illustrate the use of command substitution.The command whoami will be executed and output will be printed at that position. Whoami tells the user information
5. The \\n is an option of the echo command that tells the shell to add an extra carriage return at the end of the line.
6.The \\c tells the shell to stay on the same line.
7.  hostname command gives the hostname of the system

Unix/ Linux :: What is shell and Shell Scripts

What is Shell

Whenever you login to a Unix system you are placed in a program called the shell. The shell acts as a command interpreter; it takes each command and passes it to the operating system kernel to be acted upon. It then displays the results of this operation on completion on your screen.
There are different Flavour of shell in Unix
Finding out which shell you are using  Information about which shell you are using is held in the SHELL environment variable. The command echo $SHELL displays the value of this variable.This displays the default shell of the system. You can change the shell though in the script you execute.You can identify which shell you are presently using from the last part of the pathname.
ShellDescription
Bourne shellThis is the original Unix shell written by Steve Bourne of Bell Labs. It is available on all UNIX systems.
Below is written  in the beginning of shell scripts to specify the shell to use for the scripts. The default prompt on the Unix for this is $
#!/bin/bsh
C shellThis shell was written at the University of California, Berkeley. It provides a C-like language with which to write shell scripts – hence its name.The default prompt on the Unix for this is %
Below is written  in the beginning of shell scripts to specify the shell to use for the scripts
#!/bin/csh
Korn shellThis shell was written by David Korn of Bell labs. It is now provided as the standard shell on Unix systems. It provides all the features of the C shell with a shell programming language similar to that of the original Bourne shell. It is the most efficient shell. Consider using this as your standard interactive shell.The default prompt on the Unix for this is $Below  is written in the beginning of shell scripts to specify the shell to use for the scripts
#!/bin/ksh

What is shell Scripts:

A shell script is a collection of command which are executed in a order given. There are conditional statement and looping also available like if ,while which helps in finding if a particular value is greater than another value .
To write any comments in the shell scripts ,it has to be written with # preceded
Example
# Auther of the script is
There are some variables which are set internally by the shell and which are available to the user. They are given below in the table.
NameDescription
$1 – $9these variables are the positional parameters.
$0the name of the command currently being executed.
$#the number of positional arguments given to this invocation of the shell.
$?the exit status of the last command executed is given as a decimal string. When a command completes successfully, it returns the exit status of 0 (zero), otherwise it returns a non-zero exit status.
$$the process number of this shell – useful for including in
filenames, to make them unique.
$!the process id of the last command run in the background.
$*a string containing all the arguments to the shell, starting at $1.
Shell scripts and functions are both interpreted. This means they are not compiled.

Commands in Shell

All shells have a number of built-in commands which are executed in the shell’s own process like echo ,cd .
When you enter a command, the shell checks to see, if the command is a shell built-in such as echo or cd ,it is directly interpreted by the shell.
if the command begins with a / shell assumes that the command is the absolute path name of an executable error occurs if the executable is not found.
if not built-in and not a full pathname shell searches the directories in the PATH from left to right for the executable.Current working directory may not be in PATH
If PATH is empty or is not set, only the current working directory is searched for the executable
Unix commands are executable binary files located in directories with the name bin (for binary). Many of the commands that you use are located in the directory /usr/bin.
A typical value for the PATH variable might be:
/bin:/usr/bin:/usr/local/utils/bin:$HOME/bin