0% found this document useful (0 votes)
57 views

Shell Scripting

Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
57 views

Shell Scripting

Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 25

Shell Scripting

Open the file using an editor (e.g., "vi" or "pico".)

vi Firstshellscript.sh

All shell scripts should begin with "#!/bin/bash" or whatever other shell you prefer. This line is called the
shebang, and although it looks like a comment, it's not: it notifies the shell of the interpreter to be used
for the script. The provided path must be an absolute one (you can't just use "bash", for example), and
the shebang must be located on the first line of the script without any preceding space.

Write the code that you want to develop. E.g.

#!/bin/sh
echo "Hello World"

to make the script executable by using the "chmod" command.

chmod 744 Firstshellscript.sh

or

chmod +x Firstshellscript.sh

Execute the script. This can be done by entering the name of the script on the command line,
preceded by its path. If it's in the current directory, this is very simple:

bash$ ./Firstshellscript.sh
Hello World

If you want to see the execution step-by-step - which is very useful for troubleshooting - then
execute it with the '-x' ('expand arguments') option:

sh -x Firstshellscript.sh
+ echo 'Hello World'
Hello World

To see the contents of a script, you can use the 'cat' command or simply open the script in any
text editor:

bash$ cat Firstshellscript.sh


#!/bin/sh
echo Hello World
Comments in a Shell

In shell scripting, all lines beginning with # are comments.

# This is a comment line.


# This is another comment line.

You can also have comments that span multiple lines by using a colon and single quotes:

: 'This is a comment line.

Again, this is a comment line.

My God, this is yet another comment line.'

Note: This will not work if there is a single quote mark within the quoted contents.

Variables

As you may or may not know, variables are the most significant part of any programming
language, be it Perl, C, or shell scripting. In the shell, variables are classified as either system
variables or user-defined variables.

System Variables

System variables are defined and kept in the environment of the parent shell (the shell from
which your script is launched.) They are also called environment variables. These variable names
consist of capital letters, and can be seen by executing the 'set' command. Examples of system
variables are PWD, HOME, USER, etc. The values of these system variables can be displayed
individually by "echo"ing the system variables. E.g., echo $HOME will display the value stored in
the system variable HOME.

When setting a system variable, be sure to use the "export" command to make it available to the
child shells (any shells that are spawned from the current one, including scripts):

bash$ SCRIPT_PATH=/home/blessen/shellscript
bash$ export SCRIPT_PATH

Modern shells also allow doing all this in one pass:

bash$ export SCRIPT_PATH=/home/blessen/shellscript

User-Defined Variables

These are the variables that are normally used in scripting - ones that you don't want or need to
make available to other programs. Their names cannot start with numbers, and are written using
lower case letters and underscores by convention - e.g. 'define_tempval'.
When we assign a value to a variable, we write the variable name followed by '=' which is
immediately followed by the value, e.g., define_tempval=blessen (note that there must not be
any spaces around the equals sign.) Now, to use or display the value in define_tempval, we
have to use the echo command and precede the variable name with a '$' sign, i.e.:

bash$ echo $define_tempval


blessen

The following script sets a variable named "username" and displays its content when executed.

#!/bin/sh

username=blessen
echo "The username is $username"

Commandline Arguments

These are variables that contain the arguments to a script when it is run. These variables are
accessed using $1, $2, ... $n, where $1 is the first command-line argument, $2 the second, etc.
Arguments are delimited by spaces. $0 is the name of the script. The variable $# will display the
number of command-line arguments supplied; this number is limited to 9 arguments in the older
shells, and is practically unlimited in the modern ones.

Consider a script that will take two command-line arguments and display them. We'll call it
'commandline.sh':

#!/bin/sh

echo "The first variable is $1"


echo "The second variable is $2"

When I execute 'commandline.sh' with command-line arguments like "blessen" and "lijoe", the
output looks like this:

bash$ ./commandline.sh blessen lijoe


The first variable is blessen
The second variable is lijoe

Exit status variable

This variable tells us if the last command executed was successful or not. It is represented by $?.
A value of 0 means that the command was successful. Any other number means that the
command was unsuccessful (although a few programs such as 'mail' use a non-zero return to
indicate status rather than failure.) Thus, it is very useful in scripting.

To test this, create a file named "test", by running touch test . Then, "display" the content of
the file:

bash$ cat test


Then, check the value of $?.

bash$ echo $?
0

The value is zero because the command was successful. Now try running 'cat' on a file that isn't
there:

bash$ cat xyz1


bash$ echo $?
1

The value 1 shows that the above command was unsuccessful.

Scope of a Variable

I am sure most programmers have learned (and probably worked with) variables and the concept
of scope (that is, a definition of where a variable has meaning.) In shell programming, we also
use the scope of a variable for various programming tasks - although this is very rarely
necessary, it can be a useful tool. In the shell, there are two types of scope: global and local.
Local variables are defined by using a "local" tag preceding the variable name when it is defined;
all other variables, except for those associated with function arguments, are global, and thus
accessible from anywhere within the script. The script below demonstrates the differing scopes
of a local variable and a global one:

#!/bin/sh

display()
{
local local_var=100
global_var=blessen
echo "local variable is $local_var"
echo "global variable is $global_var"
}

echo "======================"
display
echo "=======outside ========"
echo "local variable outside function is $local_var"
echo "global variable outside function is $global_var"

Running the above produces the following output:

======================
local variable is 100
global variable is blessen
=======outside ========
local variable outside function is
global variable outside function is blessen

Note the absence of any value for the local variable outside the function.
Input and Output in Shell Scripting

For accepting input from the keyboard, we use read. This command will read values typed from
the keyboard, and assign each to the variable specified for it.

read <variable_name>

For output, we use the echo command.

echo "statement to be displayed"

Arithmetic Operations in Shell Scripting

Like other scripting languages, shell scripting also allows us to use arithmetic operations such as
addition, subtraction, multiplication, and division. To use these, one uses a function called expr;
e.g., "expr a + b" means 'add a and b'.

e.g.:

sum=`expr 12 + 20`

Similar syntax can be used for subtraction, division, and multiplication. There is another way to
handle arithmetic operations; enclose the variables and the equation inside a square-bracket
expression starting with a "$" sign. The syntax is

$[expression operation statement]

e.g.:

echo $[12 + 10]

[ Note that this syntax is not universal; e.g., it will fail in the Korn shell. The '$((...))' syntax is
more shell-agnostic; better yet, on the general principle of "let the shell do what it does best and
leave the rest to the standard toolkit", use a calculator program such as 'bc' or 'dc' and command
substitution. Also, note that shell arithmetic is integer-only, while the above two methods have
no such problem. -- Ben ]

Conditional Statements

Let's have some fun with a conditional statement like "if condition". Most of the time, we shell
programmers have situations where we have to compare two variables, and then execute certain
statements depending on the truth or falsity of the condition. So, in such cases, we have to use an
"if" statement. The syntax is show below:

if [ conditional statement ]
then
... Any commands/statements ...
fi
The script cited below will prompt for a username, and if the user name is "blessen", will display
a message showing that I have successfully logged in. Otherwise it will display the message
"wrong username".

#!/bin/sh

echo "Enter your username:"


read username

if [ "$username" = "blessen" ]
then
echo 'Success!!! You are now logged in.'
else
echo 'Sorry, wrong username.'
fi

Remember to always enclose the variable being tested in double quotes; not doing so will cause
your script to fail due to incorrect syntax when the variable is empty. Also, the square brackets
(which are an alias for the 'test' command) must have a space following the opening bracket and
preceding the closing one.

Variable Comparison

In shell scripting we can perform variable comparison. If the values of variables to be compared
are numerical, then you have to use these options:

-eq Equal to
-ne Not Equal to
-lt Less than
-le Less than or equal to
-gt Greater than
-ge Greater then or equal to

If they are strings, then you have to use these options:

= Equal to
!= Not Equal to
< First string sorts before second
> First string sorts after second

Loops

The "for" Loop

The most commonly used loop is the "for" loop. In shell scripting, there are two types: one that is
similar to C's "for" loop, and an iterator (list processing) loop.

Syntax for the first type of "for" loop (again, this type is only available in modern shells):
for ((initialization; condition; increment/decrement))
do
...statements...
done

Example:

#!/bin/sh

for (( i=1; $i <= 10; i++ ))


do
echo $i
done

This will produce a list of numbers from 1 to 10. The syntax for the second, more widely-
available, type of "for" loop is:

for <variable> in <list>


do
...statements...
done

This script will read the contents of '/etc/group' and display each line, one at a time:

#!/bin/sh

count=0
for i in `cat /etc/group`
do
count=`expr "$count" + 1`
echo "Line $count is being displayed"
echo $i
done

echo "End of file"

Another example of the "for" loop uses "seq" to generate a sequence:

#!/bin/sh

for i in `seq 1 5`
do
echo $i
done

While Loop

The "while" loop is another useful loop used in all programming languages; it will continue to
execute until the condition specified becomes false.

while [ condition ]
do
...statement...
done

The following script assigns the value "1" to the variable num and adds one to the value of num
each time it goes around the loop, as long as the value of num is less than 5.

#!/bin/sh

num=1

while [$num -lt 5]; do num=$[$num + 1]; echo $num; done

Select and Case Statement

Similar to the "switch/case" construct in C programming, the combination of "select" and "case"
provides shell programmers with the same features. The "select" statement is not part of the
"case" statement, but I've put the two of them together to illustrate how both can be used in
programming.

Syntax of select:

select <variable> in <list>


do
...statements...
done

Syntax of case:

case $<variable> in
<option1>) statements ;;
<option2>) statements ;;
*) echo "Sorry, wrong option" ;;
esac

The example below will explain the usage of select and case together, and display options
involving a machine's services needing to be restarted. When the user selects a particular option,
the script starts the corresponding service.

#!/bin/bash

echo "***********************"
select opt in apache named sendmail
do
case $opt in
apache) /etc/rc.d/init.d/httpd restart;;
named) /etc/rc.d/init.d/named restart;;
sendmail) /etc/rc.d/init.d/sendmail restart;;
*) echo "Nothing will be restarted"
esac
echo "***********************"

# If this break is not here, then we won't get a shell prompt.


break
done

[ Rather than using an explicit 'break' statement - which is not useful if you want to execute more
than one of the presented options - it is much better to include 'Quit' as the last option in the
select list, along with a matching case statement. -- Ben ]

Functions

In the modern world where all programmers use the OOP model for programming, even we shell
programmers aren't far behind. We too can break our code into small chunks called functions,
and call them by name in the main program. This approach helps in debugging, code re-usability,
etc.

Syntax for "function" is:

<name of function> ()
{ # start of function
statements
} # end of function

Functions are invoked by citing their names in the main program, optionally followed by
arguments. For example:

#!/bin/sh

sumcalc ()
{
sum=$[$1 + $2]
}

echo "Enter the first number:"


read num1
echo "Enter the second number:"
read num2

sumcalc $num1 $num2

echo "Output from function sumcalc: $sum"

Debugging Shell Scripts

Now and then, we need to debug our programs. To do so, we use the '-x' and '-v' options of the
shell. The '-v' option produces verbose output. The '-x' option will expand each simple command,
"for" command, "case" command, "select" command, or arithmetic "for" command, displaying
the expanded value of PS4, followed by the command and its expanded arguments or associated
word list. Try them in that order - they can be very helpful when you can't figure out the location
of a problem in your script..
test command or [ expr ]
test command or [ expr ] is used to see if an expression is true, and if it is true it return zero(0),
otherwise returns nonzero for false.
Syntax:
test expression OR [ expression ]

Example:
Following script determine whether given argument number is positive.

$ cat > ispostive


#!/bin/sh
#
# Script to see whether argument is positive
#
if test $1 -gt 0
then
echo "$1 number is positive"
fi

Run it as follows
$ chmod 755 ispostive

$ ispostive 5
5 number is positive

$ispostive -45
Nothing is printed

$ispostive
./ispostive: test: -gt: unary operator expected

Detailed explanation
The line, if test $1 -gt 0 , test to see if first command line argument($1) is greater than 0. If it is
true(0) then test will return 0 and output will printed as 5 number is positive but for -45 argument
there is no output because our condition is not true(0) (no -45 is not greater than 0) hence echo
statement is skipped. And for last statement we have not supplied any argument hence error
./ispostive: test: -gt: unary operator expected, is generated by shell , to avoid such error we can
test whether command line argument is supplied or not.

test or [ expr ] works with


1.Integer ( Number without decimal point)
2.File types
3.Character strings

For Mathematics, use following operator in Shell Script


Mathematical Normal Arithmetical/
Operator in  Shell Meaning Mathematical But in Shell
Script  Statements
For test For [ expr ]
      statement with statement with if
if command command
-eq is equal to 5 == 6 if test 5 -eq 6 if [ 5 -eq 6 ]
is not equal
-ne 5 != 6 if test 5 -ne 6 if [ 5 -ne 6 ]
to
-lt is less than 5<6 if test 5 -lt 6 if [ 5 -lt 6 ]
is less than
-le 5 <= 6 if test 5 -le 6 if [ 5 -le 6 ]
or equal to
is greater
-gt 5>6 if test 5 -gt 6 if [ 5 -gt 6 ]
than
is greater
-ge than or equal 5 >= 6 if test 5 -ge 6 if [ 5 -ge 6 ]
to

NOTE: == is equal, != is not equal.

For string Comparisons use

Operator Meaning
string1 = string2 string1 is equal to string2
string1 !=
string1 is NOT equal to string2
string2
string1 string1 is NOT NULL or not defined 
-n string1 string1 is NOT NULL and does exist
-z string1 string1 is NULL and does exist

Shell also test for file and directory types

Test Meaning
-s file    Non empty file
-f file    Is File exist or normal file and not a directory 
-d dir     Is Directory exist and not a file
-w file   Is writeable file
-r file    Is read-only file
-x file    Is file is executable

Logical Operators
Logical operators are used to combine two or more condition at a time

Operator            Meaning
! expression Logical NOT
expression1  -a  expression2 Logical AND
expression1  -o  expression2 Logical OR

Intersting program:-

Following script is quite intresting, it prints the chess board on screen.

$ vi chessboard
for (( i = 1; i <= 9; i++ )) ### Outer for loop ###
do
   for (( j = 1 ; j <= 9; j++ )) ### Inner for loop ###
   do
        tot=`expr $i + $j`
        tmp=`expr $tot % 2`
        if [ $tmp -eq 0 ]; then
            echo -e -n "\033[47m "
        else
            echo -e -n "\033[40m "
        fi
  done
 echo -e -n "\033[40m" #### set back background colour to black
 echo "" #### print the new line ###
done

Run the above script as follows:


$ chmod +x chessboard
$ ./chessboard

On my terminal above script produec the output as follows:


if [ $tmp -eq 0 ]; then
    echo -e -n "\033[47m "
else
    echo -e -n "\033[40m "
fi

If even number posiotion print the white colour block (using echo -e -n "\033[47m " statement);
otherwise for odd postion print the black colour box (using echo -e -n "\033[40m " statement).
This statements are responsible to print entier chess board on screen with alternet colours.
echo -e -n "\033[40m"

Make sure its black background as we always have on our terminals.

echo ""Print the blank line

Message box (msgbox) using dialog utility


$cat > dia2
dialog --title "Linux Dialog Utility Msgbox" --backtitle "Linux Shell Script\
Tutorial" --msgbox "This is dialog box called msgbox, which is used\
to show some information on screen which has also Ok button, Thanks to Savio
Lam\
and Stuart Herbert to give us this utility. Press any key. . . " 9 50

Save it and run as


$ chmod +x dia2
$ ./dia2
yesno box using dialog utility
$ cat > dia3
dialog --title "Alert : Delete File" --backtitle "Linux Shell Script\
Tutorial" --yesno "\nDo you want to delete '/usr/letters/jobapplication'\
file" 7 60
sel=$?
case $sel in
   0) echo "User select to delete file";;
   1) echo "User select not to delete file";;
   255) echo "Canceled by user by pressing [ESC] key";;
esac

Save the script and run it as:


$ chmod +x dia3
$ ./dia3

Above script creates yesno type dialog box, which is used to ask some questions to the user , and
answer to those question either yes or no. After asking question how do we know, whether user
has press yes or no button ? The answer is exit status, if user press yes button exit status will be
zero, if user press no button exit status will be one and if user press Escape key to cancel dialog
box exit status will be one 255. That is what we have tested in our above shell script as

Input Box (inputbox) using dialog utility


$ cat > dia4
dialog --title "Inputbox - To take input from you" --backtitle "Linux Shell\
Script Tutorial" --inputbox "Enter your name please" 8 60 2>/tmp/input.$$

sel=$?

na=`cat /tmp/input.$$`
case $sel in
  0) echo "Hello $na" ;;
  1) echo "Cancel is Press" ;;
  255) echo "[ESCAPE] key pressed" ;;
esac

rm -f /tmp/input.$$

Run it as follows:
$ chmod +x dia4
$ ./dia4
Inputbox is used to take input from user, In this example we are taking Name of user as input.
But where we are going to store inputted name, the answer is to redirect inputted name to file via
statement 2>/tmp/input.$$ at the end of dialog command, which means send screen output to file
called /tmp/input.$$, letter we can retrieve this inputted name and store to variable as follows
na=`cat /tmp/input.$$`.
For input box's exit status refer the following table:

Exit Status for Input


Meaning
box
0 Command is successful
1 Cancel button is pressed by user
255 Escape key is pressed by user

User Interface using dialog Utility - Putting it


all together
Its time to write script to create menus using dialog utility, following are menu items
Date/time
Calendar
Editor
and action for each menu-item is follows :

MENU-ITEM ACTION
Show current
Date/time
date/time
Calendar Show calendar
Editor Start vi Editor

$ cat > smenu


#
#How to create small menu using dialog
#
dialog --backtitle "Linux Shell Script Tutorial " --title "Main\
Menu" --menu "Move using [UP] [DOWN],[Enter] to\
Select" 15 50 3\
Date/time "Shows Date and Time"\
Calendar "To see calendar "\
Editor "To start vi editor " 2>/tmp/menuitem.$$

menuitem=`cat /tmp/menuitem.$$`

opt=$?

case $menuitem in
Date/time) date;;
Calendar) cal;;
Editor) vi;;
esac

Save it and run as:


$ rm -f /tmp/menuitem.$$
$ chmod +x smenu
$ ./smenu

--menu option is used of dialog utility to create menus, menu option take

--menu options Meaning


"Move using [UP] [DOWN],[Enter] to
This is text show before menu
Select"
15  Height of box
50  Width of box
3  Height of menu
First menu item called as tag1 (i.e. Date/time) and
Date/time    "Shows Date and Time" description for menu item called as item1 (i.e.
"Shows Date and Time")
First menu item called as tag2 (i.e. Calendar) and
description for menu item called as item2 (i.e. "To
Calendar      "To see calendar    "
see calendar")
First menu item called as tag3 (i.e. Editor) and
Editor           "To start vi editor " description for menu item called as item3 (i.e."To
start vi editor")
2>/tmp/menuitem.$$ Send selected menu item (tag) to this temporary file

After creating menus, user selects menu-item by pressing the ENTER key, selected choice is
redirected to temporary file, Next this menu-item is retrieved from temporary file and following
case statement compare the menu-item and takes appropriate step according to selected menu
item. As you see, dialog utility allows more powerful user interaction then the older read and
echo statement. The only problem with dialog utility is it work slowly.

Example programs
#!/bin/bash
#
# Linux Shell Scripting Tutorial 1.05r3, Summer-2002
#
# Written by Vivek G. Gite <[email protected]>
#
# Latest version can be found at http://www.nixcraft.com/
#

MAX_NO=0

echo -n "Enter Number between (5 to 9) : "


read MAX_NO

if ! [ $MAX_NO -ge 5 -a $MAX_NO -le 9 ] ; then


echo "I ask to enter number between 5 and 9, Okay"
exit 1
fi

clear

for (( i=1; i<=MAX_NO; i++ ))


do
for (( s=MAX_NO; s>=i; s-- ))
do
echo -n " "
done
for (( j=1; j<=i; j++ ))
do
echo -n " $i"
done
echo ""
done

for (( i=1; i<=MAX_NO; i++ ))


do
for (( s=MAX_NO; s>=i; s-- ))
do
echo -n " "
done
for (( j=1; j<=i; j++ ))
do
echo -n " ."
done
echo ""
done

echo -e "\n\n\t\t\tI hope you like it my stupidity (?)"

#
# ./ch.sh: vivek-tech.com to nixcraft.com referance converted using this tool
# See the tool at http://www.nixcraft.com/uniqlinuxfeatures/tools/
#
#!/bin/bash
#
# Linux Shell Scripting Tutorial 1.05r3, Summer-2002
#
# Written by Vivek G. Gite <[email protected]>
#
# Latest version can be found at http://www.nixcraft.com/
#

MAX_NO=0

echo -n "Enter Number between (5 to 9) : "


read MAX_NO

if ! [ $MAX_NO -ge 5 -a $MAX_NO -le 9 ] ; then


echo "I ask to enter number between 5 and 9, Okay"
exit 1
fi

clear

for (( i=1; i<=MAX_NO; i++ ))


do
for (( s=MAX_NO; s>=i; s-- ))
do
echo -n " "
done
for (( j=1; j<=i; j++ ))
do
echo -n " $i"
done
echo ""
done

for (( i=1; i<=MAX_NO; i++ ))


do
for (( s=MAX_NO; s>=i; s-- ))
do
echo -n " "
done
for (( j=1; j<=i; j++ ))
do
echo -n " ."
done
echo ""
done

echo -e "\n\n\t\t\tI hope you like it my stupidity (?)"

#
# ./ch.sh: vivek-tech.com to nixcraft.com referance converted using this tool
# See the tool at http://www.nixcraft.com/uniqlinuxfeatures/tools/
#

#!/bin/bash
#
# Linux Shell Scripting Tutorial 1.05r3, Summer-2002
#
# Written by Vivek G. Gite <[email protected]>
#
# Latest version can be found at http://www.nixcraft.com/
#

MAX_NO=0

echo -n "Enter Number between (5 to 9) : "


read MAX_NO

if ! [ $MAX_NO -ge 5 -a $MAX_NO -le 9 ] ; then


echo "I ask to enter number between 5 and 9, Okay"
exit 1
fi

clear

for (( i=1; i<=MAX_NO; i++ ))


do
for (( s=MAX_NO; s>=i; s-- ))
do
echo -n " "
done
for (( j=1; j<=i; j++ ))
do
echo -n " ."
done
echo ""
done
###### Second stage ######################
##
##
for (( i=MAX_NO; i>=1; i-- ))
do
for (( s=i; s<=MAX_NO; s++ ))
do
echo -n " "
done
for (( j=1; j<=i; j++ ))
do
echo -n " ."
done
echo ""
done

echo -e "\n\n\t\t\tI hope you like it my stupidity (?)"

#
# ./ch.sh: vivek-tech.com to nixcraft.com referance converted using this tool
# See the tool at http://www.nixcraft.com/uniqlinuxfeatures/tools/
#

=======================================================
====.#!/bin/bash
#
# Linux Shell Scripting Tutorial 1.05r3, Summer-2002
#
# Written by Vivek G. Gite <[email protected]>
#
# Latest version can be found at http://www.nixcraft.com/
#

#
# Declare the array of 5 subscripts to hold 5 numbers
#
declare nos[5]=(4 -1 2 66 10)

#
# Prints the number befor sorting
#
echo "Original Numbers in array:"
for (( i = 0; i <= 4; i++ ))
do
echo ${nos[$i]}
done

#
# Now do the Sorting of numbers
#

for (( i = 0; i <= 4 ; i++ ))


do
for (( j = $i; j <= 4; j++ ))
do
if [ ${nos[$i]} -gt ${nos[$j]} ]; then
t=${nos[$i]}
nos[$i]=${nos[$j]}
nos[$j]=$t
fi
done
done

#
# Print the sorted number
#
echo -e "\nSorted Numbers in Ascending Order:"
for (( i=0; i <= 4; i++ ))
do
echo ${nos[$i]}
done

#
# ./ch.sh: vivek-tech.com to nixcraft.com referance converted using this tool
# See the tool at http://www.nixcraft.com/uniqlinuxfeatures/tools/
#

#!/bin/bash
#
# Linux Shell Scripting Tutorial 1.05r3, Summer-2002
#
# Written by Vivek G. Gite <[email protected]>
#
# Latest version can be found at http://www.nixcraft.com/
#
n=0
hex=0
echo "Decimal to hexadecimal converter ver. b0.1"
echo -n "Enter number in decimal format : "
read n
hex=`echo "obase=16;ibase=10; $n" | bc`
echo "$n is equivalent \"$hex\" in hexadecimal"

#
# ./ch.sh: vivek-tech.com to nixcraft.com referance converted using this tool
# See the tool at http://www.nixcraft.com/uniqlinuxfeatures/tools/
#

#!/bin/bash
#
# Linux Shell Scripting Tutorial 1.05r3, Summer-2002
#
# Written by Vivek G. Gite <[email protected]>
#
# Latest version can be found at http://www.nixcraft.com/
#

n=0
on=0
fact=1

echo -n "Enter number to find factorial : "


read n

on=$n

while [ $n -ge 1 ]
do
fact=`expr $fact \* $n`
n=`expr $n - 1`
done

echo "Factorial for $on is $fact"

#
# ./ch.sh: vivek-tech.com to nixcraft.com referance converted using this tool
# See the tool at http://www.nixcraft.com/uniqlinuxfeatures/tools/
#

Pipes
A pipe is a way to connect the output of one program to the input of another program without
any temporary file.

Pipe Defined as:


"A pipe is nothing but a temporary storage place where the output of one command is stored and
then passed as the input for second command. Pipes are used to run more than two commands
( Multiple commands) from same command line."

Syntax:
command1 | command2

Examles:
 

Command using Pipes Meaning or Use of Pipes


Output of ls command is given as input to more
$ ls | more command So that output is printed one screen
full page at a time.
Output of who command is given as input to
$ who | sort  sort command So that it will print sorted list of
users
Same as above except output of sort is send to
$ who | sort > user_list
(redirected) user_list file
Output of who command is given as input to wc
$ who | wc -l  command So that it will number of user who
logon to system
Output of ls command is given as input to wc
$ ls -l | wc  -l    command So that it will print number of files in
current directory.
Output of who command is given as input to
grep command So that it will print if particular
$ who | grep raju
user name if he is logon or nothing is printed
(To see particular user is logon or not)

You might also like