Date post: | 03-Jun-2018 |
Category: |
Documents |
Upload: | saravana-sams |
View: | 230 times |
Download: | 0 times |
of 24
8/12/2019 Hands on Scripting
1/24
217324234.xlsx.ms_office
S.NO CATEGORY COMMANDS SHELL
1 BASICS OPENING SCRIPT bash
EXTENSION .sh
RUN ./filename or sh filename.sh
INCLUDE #!/bin/bash
2 OPERATIONS ASSIGNMENT var=10, a=$var
USER INPUT read a
INCLUDE SPECIAL MEANING expr 2 \* 3
PRINT STRING $myvar
PRINT STRING WITH VALUE myvar value: $myvar
space needed between operators
and not in assignment
Date = `date`
ARITHMETIC result=`expr $num1 \* $num2`
PRINT echo $resultVALID OPERATORS +,-,*,/,%,=,
VARIABLES SCALARS
ARRAYS
ASSOCIATIVE ARRAYS
3 SYMBOLS COMMENT #
STATEMENTS SEPERATOR ;
ESCAPE SEQUENCE \
VARIABLE $STRING "" OR ''
COMMAND EXECUTION ` OR $()
BLOCK OF CODE {}
NO OPERATION :
TEST CONDITION []
STANDARD OPERATORS STDIN(0)
STDOUT(1)
HA
INT
INP
8/12/2019 Hands on Scripting
2/24
217324234.xlsx.ms_office
STDERR(2)
REDIRECTION INPUT
APPEND MODE >>
3 DEBUG EXECUTED COMMANDS sh -x filename.sh
LINES READ sh -v filename.sh
4 LOOP FOR
for loop-variable in members
do
command
command
done
can also be used for the block
instead of do done
FOREACH NA
WHILE
while [ condition ]
do
command
command
done
There MUST be a space after [ and
before ]
8/12/2019 Hands on Scripting
3/24
217324234.xlsx.ms_office
UNTIL
until [ condition ]
do
command
command
done
5 CONDITION EQUAL TO $a -eq 0 , $STRING = $STRING2
NOT EQUAL TO $a -ne 1 , $STRING != $STRING2
LESS THAN $a -lt 2
GREATER THAN $a -gt 3
LESS THAN OR EQUAL TO $a -le 4
GREATER THAN OR EQUAL TO $a -ge 5
6 BRANCHING IF ELSE
if condition1
then commands1
else commands3
fi
IF ELSE IF ELSE
if condition1
then commands1
elif condition2 then commands2
else commands3
fi
SWITCH CASE
case $cal in
add)
;;
sub)
;;
mul)
;;
div)
;;
esac
C
8/12/2019 Hands on Scripting
4/24
217324234.xlsx.ms_office
UNLESS NA
7 COMMAND LINE SCRIPT NAME $0 (./FILENAME.sh)
ADDITIONAL ARGUMENTS $1
ARGUMENT COUNT $#
ENUMERATES $@ OR $*
EXIT VALUE OF LAST COMMAND $?
LINE NUMBER
REMOVES NEW LINE
REMOVES LAST CHARACTERanonymous VARIABLE
8 FUNCTIONS DEFINITION
function func_name
{
Body of function
}
Note:- all the arguments passed to
the function will be stored to $1, $2
variables
IMPORT source ./scripname
9 SUB SHELL RUNNING IN PARENT . ./FILENAME.sh
CHILD Default one
CO
mailto:$@%20OR%20$*mailto:$@%20OR%20$*8/12/2019 Hands on Scripting
5/24
217324234.xlsx.ms_office
10 CONFIGURATION
.bash_profile
.bashrc
.bash_logout
11 SIGNALS TRAP A SIGNAL $ trap command signal
IGNORE A SIGNAL $ trap signalRESET A SIGNAL $ trap signal
12 LISTS CREATE LIST NA
OPERATIONS INDEXSORT
CONCATENATE
APPEND
LENGTH
INSERT
RANGE
DELETE
REVERSE
DELETE AT LAST
13 NAMESPACE
13 STRING EQUAL
LAST
It encapsulates the commands and variables to ensure that they won't
interfere with the commands and variables of other namespaces
8/12/2019 Hands on Scripting
6/24
217324234.xlsx.ms_office
LENGTH
RANGE
REPLACE
INDEX
MATCH
ADDITIONAL OPERATIONS
TO BINARY STRING
TO TCL STRING
SCAN
parses string using conversion
specifiers
14 SCOPE NA
15 INTERNALS NA
16 FILE ALL COMMANDS
OPEN
SEEK
MODE
diamond operator
17 ARRAYS INSERT AT LAST
ARRAY LENGTH
INSERT AT FIRST
REMOVES AT LAST
REMOVES AT FIRST
REVERSE
SORT
NA
NA
8/12/2019 Hands on Scripting
7/24
217324234.xlsx.ms_office
JOIN
SPLIT
ASSOCIATIVE ARRAY DECLARE
DEFINE
ITERATE
KEYS
VALUES
18 HELP INFO man command
SOURCE NA
SOCKET
ERROR INFO
WINDOW SHELL
NA
8/12/2019 Hands on Scripting
8/24
217324234.xlsx.ms_office
19 PATTERN MATCHING SYNTAX
OPTIONS !~
/g
/i
/x
s / pattern / replace /
tr / characters / repl-characters /
split ( /Pattern/, String )REFE
8/12/2019 Hands on Scripting
9/24
217324234.xlsx.ms_office
TCL PERL
tclsh perl -e commands
.tcl .pl
tcl filename.tcl perl filename.pl
#!/usr/bin/perl
ALL LINES END WITH ;
set a 22,set b $a
$name = Aricent Tech;
( $a, $b) = ($c, $d); # Same as $a=$c; $b=$d;
gets stdin var $inputline = ;
expr 2 \* 3 also expr 2*3 works fine
set b {[expr $a+10]}
"a is $a" print Length of name : , length($name), \n;
spaces not needed between operators
print "@array"; #print whole array with spaces
print @array; #print whole array without spaces
set Date [date] system(date);$Date = date`;
set b [expr $a+10] $S = $A + $B
puts "x is $x" print "@array"; print $s;
$scalars
@arrays
set student(name) John %associative_arrays
# # , =begin =cut
stdin STDIN(0)
stdout STDOUT(1)
NDS ON SCRIPTING
ODUCTION TO VARIOUS SHELLS
T ASSIGNMENTS AMD OUTPUT
SYMBOLS AND OPTIONS
8/12/2019 Hands on Scripting
10/24
217324234.xlsx.ms_office
stderr STDERR(2)
ERROR HANDLING
catch {expr {2 +}} msg
use warnings
use strict
error "bad argument"
The next command starts the next iteration of the
loop.
The last command immediately exits the loop inquestion.
The redo command is used to start processing of the
current iteration again.
for {set x 0} {$x= 0} {
puts "[incr lineCount]: $line"
}
while (CONDITION) {
# Code block executed if condition is true.
}
LOOPING CONSTRUCTS
8/12/2019 Hands on Scripting
11/24
217324234.xlsx.ms_office
NA
until (CONDITION) {
# Code block executed while condition is false.
}
$a == 0 , $STRING == $STRING2 $STRING eq $STRING2, $a == 0
$a != 1 , $STRING != $STRING2 $STRING ne $STRING2, $a != 1
$a < 2 $STRING lt $STRING2, $a < 2
$a > 3 $STRING gt $STRING2, $a > 3
$a = 5
if {expr1} {
puts "vbl is one ; #body1
} else {
puts "vbl is not one or two"
}
if (CONDITION) {
# Code block executed if condition is true.
} else {
# Code block executed if condition is false.
}
if {expr1} {
puts "vbl is one ; #body1
} elseif {$vbl == 2} {
puts "vbl is two } else {
puts "vbl is not one or two"
}
if (expr1){
puts "vbl is one ; #body1
} elsif ($vbl == 2){ puts "vbl is two
} else {
puts "vbl is not one or two"
}
set foo "abc"
switch abc
a - b {expr 1}
$foo {expr 2}
default {expr 3}
RANCHING STATEMENTS
ONDITIONAL OPERATORS
8/12/2019 Hands on Scripting
12/24
217324234.xlsx.ms_office
NA
unless (CONDITION) {
# Code block executed if condition is false.
} elsif (CONDITION FALSE 1) {
# Code block executed if condition is true.
} else (CONDITION FALSE 2) {
# Code block executed if condition is true.
}
$argv0 $0 for script name. Arguments stored in @ARGV
$argv1 $ARGV[0]
$argc $#ARGV+1
$argv @ARGV
$.
chomp ($price);
chop($price);$_
proc decr {x {y 1}} {
expr $x-$y
}
sub (Arguments) {
}
Parameters passed to a subroutine can be accessed in
a subroutine using a special variable @_
proc sum args { set s 0
foreach i $args { incr s $i } return $s
}
sum 1 2 3 4 5
Package package_name;
BEGIN {
# initialization statement
}
Sub function_name {
#body of function
}
Return 1;
END {
#clean up statement
}
Save this file as package_name.pm
source ./scripname
use package_name;
package_name::function_name();
catch {exec grep foo
8/12/2019 Hands on Scripting
13/24
217324234.xlsx.ms_office
fconfigure $f -translation binary
FOR BINARY ENCODED FILE HANDLER
set tList {{one} {two} {three}}
Or
set tList [list one two three]
Or
set tList *split one .two .three .+
lindex {a b {c d e} f} 2 --> c d e
lsort {red green blue} -->blue green red
concat a b {c d e} {f {g h}} -->a b c d e f { g h }
lappend var 2 --> 2 APPENDED IN END
llength {a b c d e} --> 5
linsert $tList 1 --> INSERT IN INDEX 1
lrange {a b c d e} 0 1 --> RETURNS a b
namespace eval Counter {
namespace export bump
variable num 0
proc bump {} {
variable num
incr num
}
}
One can then access proc bump using
Counter::bump from global namespace
set isitEqual [string equal $x1 $string] ; #
Returns 1 if equal else 0.
string last a 0a23456789abcdef 15
# will return 10. Here index within which the
occurrence has to be found is 15.
LIST DATA STRUCTURES
STRING OPERATIONS
8/12/2019 Hands on Scripting
14/24
217324234.xlsx.ms_office
string length string;
string range string first last
string replace string first last ?newstring?
string index string charIndex
string match ?-nocase? pattern string
regexp format split binary regsub scan joinappend
formatString ?arg arg ...?
string formatString ?varName varName ...?
set string "08:08" ;# *Not* octal!
if {[scan $string "%d:%d" hours minutes] != 2} {
error "not a valid time string"
}
global uplevel upvar my local
info rename trace
open gets seek flush glob file close read tell cd
pid puts source eof pwd
set fl *open trn w+
open (FILE_HANDLE, EXPR ); EXPR = MODE + FILENAME
open (FILEHANDLE, "
8/12/2019 Hands on Scripting
15/24
217324234.xlsx.ms_office
$URL = join (., @url);
@fields = split ( / : / , "1:2:3:4:5");
set student(name) John
% geography = (Bangalore , India , London,
England);
% geography = (Bangalore" => India",
London" => England");
($city, $country) = each %geography;
@cities = keys %geography;
@countries = values %geography;
% info commands s* socket subst split source switch spinbox scale
set scan seek scrollbar selection string
perldoc -f perlfunction
man n command
Evaluate a file or resource as a Tcl script
source
socket option addr port
server option creates server socket
Global variable errorInfo provides stack trace
set errorInfo
Wish: Windowing Shell
button .hello -text "Hello, world" -command
exit
pack .hello
MAY I HELP YOU
REGULAR EXPRESSIONS
8/12/2019 Hands on Scripting
16/24
217324234.xlsx.ms_office
regexp -all -- {\S+} $line pattern_to_match =~ /pattern/;
if (m/$pattern/) {
print "Found $pattern \n";
}
is just the negative of =~
global -This option finds all occurrences of the
pattern in the string. A list of matches is returned.
case-insensitive - This option ignores the case ofcharacters in the string.
Ignore whitespaces
Replaces the sub- string matched by pattern with
replace (once) and returns the number of
replacements (obviously 0 or1)
Translates characters (one by one), as specified by
characters with
repl-characters and returns the number of
replacements.tr is always global
my @fields = split ( /\s+/, $string);RENCING & DE REFERENCING
8/12/2019 Hands on Scripting
17/24
217324234.xlsx.ms_office
PYTHON
python
.py
python filename.py, execfile('script.py')
#!/usr/bin/python
x = [0,1,2],
writer=raw_input('Please enter') or
year=int(year)
\*
os.system(command) or
from datetime import date
now = date.today()
s = s + i
print 'Hello world' OR print s
#, Triple quotes - multi line string
sys.stdin
sys.stdout
8/12/2019 Hands on Scripting
18/24
217324234.xlsx.ms_office
sys.stderr
try: n = float(s)
numbers.append(s)
except ValueError, msg:
not_numbers.append(str(msg))
for i in range(1,7):
while condition:
action
8/12/2019 Hands on Scripting
19/24
217324234.xlsx.ms_office
s == 'string', a == 0
a != 1 , STRING != 'STRING2'
a < 2
a > 3
a = 5
if condition:
action
if condition1:
action1elif condition2:
action2
else:
action3
8/12/2019 Hands on Scripting
20/24
217324234.xlsx.ms_office
sys.argv[0]
sys.argv
def func(args):
Actually returns a value anyway: 'None'
import module
module.submodule.x
OR
from module import submodule
submodule.x
map(func,list), reduce(func,list),
filter(func,list)
8/12/2019 Hands on Scripting
21/24
217324234.xlsx.ms_office
shoplist = ['apple', 'mango', 'carrot',
'banana']
olditem = shoplist[0]shoplist.sort()
shoplist.append('rice')
len(shoplist)
shoplist[1:3]
del shoplist[0]
shoplist.reverse()
shoplist.pop()
re MODULE has re.compile, obj.match,
re.search, obj.group,re.split,re.findall,
re.finditer, re.sub,
8/12/2019 Hands on Scripting
22/24
217324234.xlsx.ms_office
hollow=hollow.replace('Shadow','Light')
index=song.find('a')
Built-in (Python),Global (module),Local
(function)
F=open(filename,w)
f.write(poem)
f.close()
line = f.readline()
TUPLE
zoo = ('wolf', 'elephant', 'penguin') new_zoo
= ('monkey', 'dolphin', zoo)
len(new_zoo)
new_zoo[2][2] --> penguin
8/12/2019 Hands on Scripting
23/24
217324234.xlsx.ms_office
DICTIONARY
ab = { 'Swaroop' :
'Larry' : '[email protected]',
'Matsumoto' : '[email protected]','Spammer' : '[email protected]'
}
ab['Guido'] = '[email protected]'
del ab['Spammer']
ab.items():
ab.has_key('Guido')
help()
8/12/2019 Hands on Scripting
24/24
217324234.xlsx.ms_office
import re
seq =
"MAKEVFSKRTCACVFHKVHAQPNVGITR"
zinc_finger = re.compile('C.C..H..H') #compile regular expression pattern
print zinc_finger.findall(seq)