Beruflich Dokumente
Kultur Dokumente
Variables ...................................................................................................................................10
Mathematical operators.............................................................................................................30
Logical Operators......................................................................................................................33
Conditional statements..............................................................................................................38
Shell Introduction
Normally shells are interactive. It means shell accept command from you (via
keyboard) and execute them. But if you use command one by one (sequence of 'n'
number of commands) , the you can store this sequence of command to text file
and tell the shell to execute this text file instead of entering the commands. This is
known as shell script.
Shell script defined as:"Shell Script is series of command written in plain text file.
Shell script is just like batch file is MS-DOS but have more power than the MS-
DOS batch file."
Variables in Shell
To process our data/information, data must be kept in computers Random
Access Memory.
RAM memory is divided into small locations, and each location had unique
number called memory location/address, which is used to hold our data.
Programmer can give a unique name to this memory location/address called
memory variable or variable
In Linux (Shell), there are two types of variable:
System variables - This type of variable defined in CAPITAL
LETTERS. These are created and used by the Linux system.
User defined variables (UDV) - This type of variable defined in
lower letters. These are create and used by the user.
Wild cards
Pipe Concept
You can connect two commands together so that the output from one
program becomes the input of the next program. Two or more commands
connected in this way form a pipe.
To make a pipe, put a vertical bar (|) on the command line between two
commands.
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
print sorted list of users and output is sent to (redirected) list_of_user file
For this we can execute,
$ who | sort > list_of_user
Same as above except output of sort is send to (redirected) list_of_user
if <condition> ; then
commands
fi
since we are giving then on same line where is if condition we give ; before then otherwise
same can be writtent without ; as below -
if <condition>
then
commands..
fi
Syntax:
test expression OR [ expression ]
Example: Following script determine whether given argument number is
positive.
when you give expression without test command you just mention it in
[ expression ]
NOTE -Please make sure space after "[" and before
"]"
if you try without space and it will give an error
Example 1 -
if test $1 -gt 0
then
echo "$1 number is positive"
fi
#same can be written without test as below
#NOTE -Please make sure space after "[" and before "]"
#try without space and it will give an error
if [ $1 -lt 0 ]
then
echo "$1 number is Negative"
fi
Run it as follows
$ chmod 744 check_postive.sh
$ ./check_postive.sh 7
7 number is positive
$ ./check_postive.sh -49
-49 number is Negative
$ check_postive
./check_postive: test: -gt: unary operator expected
Since test is a shell command, use "help test" to see a complete list.
Expression Description
file1 -nt file2 True if file1 is newer than (according to modification time) file2
Example 2 -
if [ -f mytest.txt ]; then
echo "You have a mytest.txt. Things are fine."
else
echo "Yikes! You have no mytest.txt!"
fi
if test -f mytest.txt
then
echo "Awesome! You have a mytest.txt. Things are fine."
else
echo "O O! You have no mytest.txt!"
fi
fi
rm mytest.txt
run again-
./test_myfile.sh
similarly you may try all other options with test to verify various things. we will look that with our
real time examples in next chapters.
You can do -
Value1 + Value2 arithmetic sum of Value1 and Value2.
Value1 - Value2 arithmetic difference of Value1 and Value2.
Value1 * Value2 arithmetic product of Value1 and Value2.
Value1 / Value2 arithmetic quotient of Value1 divided by Value2.
Value1 % Value2 arithmetic remainder of Value1 divided by Value2.
Example 4 -
expr 8 % 5
3
You can use the following comparision operators with the expr command:
Returns value 1 if condition is true otherwise 0.
Value1 < Value2 : Returns 1 if Value1 is less than Value2. otherwise zero.
Value1 <= Value2 : Returns 1 if Value1 is less than or equal to Value2. otherwise zero.
Value1 > Value2 : Returns 1 if Value1 is greater than Value2. otherwise zero.
Value1 >= Value2 : Returns 1 if Value1 is greater than or equal to Value2. otherwise zero.
Value1 = Value2 : Returns 1 if Value1 is equal to Value2. otherwise zero.
Value1 != Value2 : Returns 1 if Value1 is not equal to Value2. otherwise zero.
Value1 | Value2 : Returns Value1 if Value1 is neither null nor zero. Otherwise Value2.
Value1 & Value2 : Returns Value1 if both Value1 and Value2 is neither null nor zero. Otherwise
0.
expr 2 \< 3
expr 5 \<= 5
expr 3 \> 8
expr 3 \>= 8
expr 9 = 9
expr 9 != 81
expr 2 \| 6
expr 0 \| 7
expr 2 \& 7
expr 6 \& 4
6
expr 7 \& 0
expr 0 \& 4
Depending on what type of work you want your scripts to do you may end up using arithmetic a
lot or not much at all. It's a reasonable certainty however that you will need to use arithmetic at
some point.
Normal Arithmetical/
Mathematical Operator
Meaning Mathematical But in Shell:
in Shell Script
Statements
press ctrl+c
ls l
chmod 777 math_opr.sh
./math_opr.sh
Operator Meaning
string1 = string2 string1 is equal to string2
#!/bin/bash
#declare strings
#script to compare strings
str1="ABC"
str2="XYZ"
str3=
if [ "$str1" = "XYZ" ]; then
echo "str1 Matched"
else
echo "str1 is NOT Matched $str1"
fi;
if [ -z "$str3" ]; then
echo "str3 IS NULL"
else
echo "str3 is NOT NULL"
fi;
ls l
Logical Operators
Operator Meaning
! expression Logical NOT
expression1 -a expression2 / && Logical AND
expression1 -o expression2 / || Logical OR
Not: This is logical negation. This inverts a true condition into false and vice versa.
AND you can use a or && (most common) both conditions need to be satisfied
if [ $condition1 ] && [ $condition2 ]
# Same as: if [ $condition1 -a $condition2 ]
# Returns true if both condition1 and condition2 hold true...
OR you may use o or || (most common) one of condition needs to be true
if [ $condition1 ] || [ $condition2 ]
# Same as: if [ $condition1 -o $condition2 ]
# Returns true if either condition1 or condition2 holds true
str1="ABC"
str2="XYZ"
str3="ABC"
ls l
chmod 777 logic_opr.sh
./ logic_opr.sh
Example 2
Let us write a script to print command line arguments.
We will be using command line arguments in many of our examples so please understand it
properly.
You may not assign command line arguments in script so following is Invalid
$1 = ABC
$2 = Name
In real time situations, shell script may need to interact with users. You can
accomplish this as follows:
Use command line arguments (args) to script when you want interaction i.e. pass
command line args to script as :
$ ./script_name.sh fo 4
where fo & 4 are command line args passed to shell script sutil.sh.
OR
Use statement like echo and read to read input into variable from the prompt. For
e.g. Write script as:
$ cat > user_input
#
# using echo and read command for user interaction
#
echo "Name please :"
read name
echo "Last Name please :"
read l_name
echo "Hello $name $l_name, How are you?"
Conditional statements
if...else...fi example
Let us look at an example to test if a given number is positive or negative,
$ vi test_number.sh
#!/bin/sh
#
# Script to see whether argument is positive or
negative
# if no arguments are provided
if [ $# -eq 0 ]
then
echo "$0 : You must supply at least one integers"
exit 1
fi
if test $1 -gt 0
then
echo "$1 number is positive"
else
echo "$1 number is negative"
fi
Try it as follows:
$ chmod 755 test_number.sh
$ test_number.sh 8
8 number is positive
$ test_number.sh -47
-47 number is negative
$ test_number.sh
./test_number.sh : You must supply at least one integers
$ test_number.sh 0
0 number is negative
First script checks whether command line argument is given or not, if not
given then it print error message as "./test_number.sh : You must
give/supply one integers".
if statement checks whether number of argument ($#) passed to script is not
equal (-eq) to 0, if we passed any argument to script then this if statement is
false and if no command line argument is given then this if statement is true.
The echo command i.e. echo "$0 : You must give/supply one integers"
$0 will print Name of script
Rest after $0: will print this error message
And finally statement exit 1 causes normal program termination with exit
status 1 (nonzero means script is not successfully run).
The last sample run $ test_number.sh 0 , gives output as "0 number is
negative", because given argument is not > 0, hence condition is false and
it's taken as negative number. To avoid this replace second if statement with
if test $1 -ge 0.
$ chmod +x nestedif.sh
$ ./nestedif.sh
1. Mac
2. Linux
Select you os choice [1 or 2]? 1
You Pick up Mac
$ ./nestedif.sh
1. Mac
2. Linux
Select you os choice [1 or 2]? 2
You Pick up Linux
$ ./nestedif.sh
1. Mac
2. Linux
Select you os choice [1 or 2]? 3
What you don't like Mac/Linux OS.
Note that Second if-else construct is nested in the first else statement. If the
condition in the first if statement is false the the condition in the second if
statement is checked. If it is false as well the final else statement is executed.
case $rental in
"car") echo "For $rental USD20 per mile";;
"van") echo "For $rental USD10 per mile";;
"jeep") echo "For $rental USD5 per mile";;
"cycle") echo "For $rental 20 cents per mile";;
*) echo "Sorry, I cannot get a $rental for you";;
esac
We will check first, that if $1(first command line argument) is given or not,
if NOT given set value of rental variable to "*** Unknown vehicle ***",
if command line arg is supplied/given set value of rental variable to given
value (command line arg).
The $rental is compared against the patterns until a match is found.
For first test run its match with van and it will show output "For van USD10
per mile."
For second test run it print, "For car USD20 per mile".
And for last run, there is no match for Ford, hence default i.e. *) is executed
and it prints, "Sorry, I cannot get a Ford for you".
Please Note that: esac is always required to indicate end of case statement.
for loops iterate through a set of values until the list is exhausted:
Syntax:
for { variable name } in { list }
do
execute one for each item in the
list until the list is
not finished (And repeat all
statement between do and done)
done
The for loop first creates i variable and assigned a number to i from the list of
number from 1 to 9, The shell execute echo statement for each assignment of i.
(This is usually know as iteration) This process will continue until all the items in
the list were not finished, because of this it will repeat 9 echo statements.
To make you idea more clear let us consider one more example:
$ cat > multiply_table.sh
#!/bin/sh
#
#Script to test for loop
#
#
if [ $# -eq 0 ]
then
echo "Error - Number missing form command line
argument"
echo "Syntax : $0 number"
echo "Use to print multiplication table for given
number"
exit 1
fi
n=$1
for i in 1 2 3 4 5 6 7 8 9 10
do
echo "$n * $i = `expr $i \* $n`"
done
For first run, above script print multiplication table of given number where i
= 1,2 ... 10 is multiply by given n (here command line argument 9) in order
to produce multiplication table as
9 * 1 = 9
9 * 2 = 18
...
..
9 * 10 = 90
And for second test run, it will print message -
Error - Number missing form command line argument
Syntax : ./multiply_table number.sh
$ vi nest_for.sh
for (( i = 1; i <= 5; i++ )) ### Outer ###
do
done
Run the above script as follows:
$ chmod +x nest_for.sh
$ ./nest_for.sh
1 1 1 1 1
2 2 2 2 2
3 3 3 3 3
4 4 4 4 4
5 5 5 5 5
Here, for each value of i the inner loop is cycled through 5 times, with the
variable j taking values from 1 to 5. The inner for loop terminates when the
value of j exceeds 5, and the outer loop terminals when the value of i
exceeds 5.
while [ condition ]
do
command1
command2
command3
..
....
done
do Start loop
if [ $# -eq 1 ]
then
var_num=$1
else
echo -n "Enter a Number :"
read var_num
fi
f1=0
f2=1
for (( k=0;k<=var_num;k++ ))
do
echo -n "$f1 "
fn=$((f1+f2))
f1=$f2
f2=$fn
done
1
12
123
1234
12345
123456
For example if user enter 123 as input then 321 is printed as output.
example -
123
first iteration reminder = 3
sd = 3
first iteration digit = 12
second iteration reminder = 2
sd =2
second iteration digit = 1
sd =1
script -
What is Processes
When you execute a program on your UNIX system, the system creates a
special environment for that program. This environment contains everything
needed for the system to run the program as if no other program were
running on the system.
Whenever you issue a command in UNIX, it creates, or starts, a new
process. When you tried out the ls command to list directory contents, you
started a process. A process, in simple terms, is an instance of a running
program.
$ ls -lR
ls command or a request to list files in a directory and all subdirectory in
your current directory - It is a process.
Process defined as:
"A process is program (command given by user) to perform specific Job. In
Linux when you start process, it gives a number to process (called PID or
process-id), PID starts from 0 to 65535."
Why Process required
As You know Linux is multi-user, multitasking Os. It means you can run
more than two process simultaneously if you wish. For e.g. To find how
many files do you have on your system you may give command like:
$ ls / -R | wc -l
This command will take lot of time to search all files on your system. So you
can run such command in Background or simultaneously by giving
command like
$ ls / -R | wc -l &
The ampersand (&) at the end of command tells shells start process (ls / -R
| wc -l) and run it in background takes next command immediately.
Process & PID defined as:
"An instance of running command is called process and the number printed
by shell is called process-id (PID), this PID can be use to refer specific
running process."
ps ax | grep To see if a particular process is For e.g. you want to see whether
process-U-want-to running or not. For this purpose you Apache web server process is
see have to use ps command in running or not then give
combination with the grep command command
$ ps ax | grep httpd
What is function?
Need of function?
Function examples
Example 1
#!/bin/bash
# Basic function
print_something () {
echo Hello I am a function
return
}
print_something
Function example 2
Passing Arguments
It is often the case that we would like the function to process some data for us. We
may send data to the function in a similar way to passing command line arguments
to a script. We supply the arguments directly after the function name. Within the
function they are accessible as $1, $2, etc.
arguments_example.sh
#!/bin/bash
# Passing arguments to a function
print_something () {
echo Hello $1
return
}
print_something Tim
print_something Kush
This is a special Linux file which is used to send any unwanted output from
program/command. It discards all data written to it without displaying it on
screen.
Syntax:
command > /dev/null
Example:
$ ls -al > /dev/null
Output of above command is not shown on screen it will send to this special
file instead.
7. Logical AND operator can be used with more than 1 conditions. Also
known as &&
Syntax:
command1 && command2
command2 is executed if, and only if, command1 runs
successfully which means returns an exit status of
zero.
Example 1: Create folder, if the folder creation is successful, then only change the directory.
Like this, you can use it at various places effectively to save your valuable time.
Example 1
If or_dir doesnt exists then it will create.
[ -d or_dir ] || mkdir or_dir
Example 2
If or_file doesnt exists then create it by coping contents from mytest.txt
[ -f or_file ] || cat > or_file < mytest.txt
Essential Utilities
vi bye.txt
how are you?
bye
Filter adjacent matching lines from INPUT (or standard input), writing to
OUTPUT (or standard output).
Usage: uniq [OPTION]... [INPUT [OUTPUT]]
Here is the man page result for uniq,
uniq --help that is of interest to us.
With no options, matching lines are merged to the first
occurrence.
sed -e '1,10d' deletes the first 10 lines, ie, the 10 newest files.
You need to use the ps command, pstree command, and pgrep command
to view a snapshot of the current processes.
pgrep looks through the currently running processes and lists the process IDs
Which matches the selection criteria to screen.
pgrep -u kish
You can send various signals to commands / process and shell scripts using
the, pkill command, kill command, and killall command.
Terminating Processes
To terminate foreground process press CTRL+C to send an interrupt signal to
any running command.
To terminate unwanted background process use kill command with -9 signal.
kill -TERM pid
kill -KILL pid
To stop (suspend) a foreground process hit CTRL+Z
To resume the foreground process use the fg command, enter:
fg jobid
killall sends a signal to all processes running any of the specified commands .
If no signal name is specified, SIGTERM is sent.
To terminate all process (child and parent), enter:
killall processName
Below is the commonly used signal numbers, description and whether they
can be trapped or not:
The trap statement
trap defines and activates handlers to be run when the shell receives signals
or other special conditions.
Try the following example at a shell prompt (make sure abc.txt doesn't exits).
Define a shell variable called $file:
file=abc.txt
Now, try to remove $file, enter:
rm $file
Sample output:
rm: cannot remove `abc.txt': No such file or directory
Now trap rm command:
trap "rm $file; exit" 0 1 2 3 15
Display list of defined traps, enter:
trap
2) w
read -p "Press [Enter] key to continue..." readKey ;;