Hands On Scripting
Hands On Scripting
Hands On Scripting
ms_office
HANDS ON
S.NO CATEGORY COMMANDS
OPENING SCRIPT EXTENSION RUN INCLUDE
SHELL
bash .sh ./filename or sh filename.sh #!/bin/bash
INTRODUCTION
1 BASICS
INPUT ASSIGNM
2 OPERATIONS ASSIGNMENT USER INPUT INCLUDE SPECIAL MEANING PRINT STRING PRINT STRING WITH VALUE var=10, a=$var read a expr 2 \* 3 $myvar myvar value: $myvar
SYMBOLS
3 SYMBOLS COMMENT STATEMENTS SEPERATOR ESCAPE SEQUENCE VARIABLE STRING COMMAND EXECUTION BLOCK OF CODE NO OPERATION TEST CONDITION STANDARD OPERATORS # ; \ $ "" OR '' ` ` OR $() {} : [] STDIN(0) STDOUT(1)
217324234.xlsx.ms_office STDERR(2) REDIRECTION INPUT < OUTPUT > APPEND MODE >>
3 DEBUG
sh -x filename.sh sh -v filename.sh
LOOPING
for loop-variable in members do command command done ,- can also be used for the block instead of do done 4 LOOP FOR
FOREACH
NA while [ condition ] do command command done There MUST be a space after [ and before ]
WHILE
217324234.xlsx.ms_office until [ condition ] do command command done UNTIL 5 CONDITION EQUAL TO NOT EQUAL TO LESS THAN GREATER THAN LESS THAN OR EQUAL TO GREATER THAN OR EQUAL TO $a -eq 0 , $STRING = $STRING2 $a -ne 1 , $STRING != $STRING2 $a -lt 2 $a -gt 3 $a -le 4 $a -ge 5
CONDITION
BRANCHING
if condition1 then commands1 else commands3 fi 6 BRANCHING IF ELSE if condition1 then commands1 elif condition2 then commands2 else commands3 fi IF ELSE IF ELSE case $cal in add) ;; sub) ;; mul) ;; div) ;; esac
SWITCH CASE
217324234.xlsx.ms_office
UNLESS 7 COMMAND LINE SCRIPT NAME ADDITIONAL ARGUMENTS ARGUMENT COUNT ENUMERATES EXIT VALUE OF LAST COMMAND LINE NUMBER REMOVES NEW LINE REMOVES LAST CHARACTER anonymous VARIABLE
NA $0 (./FILENAME.sh) $1 $# $@ OR $* $?
COMMAND L
FUNCTI
function func_name { Body of function } Note:- all the arguments passed to the function will be stored to $1, $2 variables 8 FUNCTIONS DEFINITION
EX
217324234.xlsx.ms_office .bash_profile .bashrc .bash_logout 10 CONFIGURATION 11 SIGNALS TRAP A SIGNAL IGNORE A SIGNAL RESET A SIGNAL $ trap command signal $ trap signal $ trap signal
LIST DATA
12 LISTS
NA INDEX SORT CONCATENATE APPEND LENGTH INSERT RANGE DELETE REVERSE DELETE AT LAST
13 NAMESPACE
It encapsulates the commands and variables to ensure that they won't interfere with the commands and variables of other namespaces
STRING O
13 STRING EQUAL
LAST
NA
NA
SCAN
SCOPE O
14 SCOPE 15 INTERNALS NA NA
FILE H
16 FILE ALL COMMANDS
OPEN SEEK
NA
TOUR W
ARRAY LENGTH INSERT AT FIRST REMOVES AT LAST REMOVES AT FIRST REVERSE SORT
NA
ASSOCIATIVE ARRAY
MAY I
18 HELP
INFO
man command
SOURCE SOCKET
NA
ERROR INFO
WINDOW SHELL
REGULAR
217324234.xlsx.ms_office
19 PATTERN MATCHING
SYNTAX
OPTIONS
!~
/g /i /x
s / pattern / replace /
REFERENCING &
217324234.xlsx.ms_office
HANDS ON SCRIPTING
TCL INTRODUCTION TO VARIOUS SHELLS
tclsh .tcl tcl filename.tcl perl -e commands .pl perl filename.pl #!/usr/bin/perl ALL LINES END WITH ; $name = Aricent Tech; ( $a, $b) = ($c, $d); # Same as $a=$c; $b=$d; $inputline = <STDIN>;
PERL
print "@array"; #print whole array with spaces print @array; #print whole array without spaces
stdin stdout
STDIN(0) STDOUT(1)
ERROR HANDLING
LOOPING CONSTRUCTS
The next command starts the next iteration of the loop. The last command immediately exits the loop in question. The redo command is used to start processing of the current iteration again.
for (INITIALIZATION; WHILECONDITION;INCREMENT/DECREMENT) { Statements executed } foreach my $LOOP_VAR (@ARRAY) { #statements executed for each array element }
foreach i {1 2 3 4 5} {
217324234.xlsx.ms_office
NA
until (CONDITION) { # Code block executed while condition is false. } $STRING eq $STRING2, $a == 0 $STRING ne $STRING2, $a != 1 $STRING lt $STRING2, $a < 2 $STRING gt $STRING2, $a > 3 $STRING cmp $STRING2, $a <= 4 $a >= 5 if (CONDITION) { # Code block executed if condition is true.
CONDITIONAL OPERATORS
$a == 0 , $STRING == $STRING2 $a != 1 , $STRING != $STRING2 $a < 2 $a > 3 $a <= 4 $a >= 5
BRANCHING STATEMENTS
if {expr1} { puts "vbl is one ; #body1 } else { puts "vbl is not one or two" } 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}
217324234.xlsx.ms_office 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. } NA
FUNCTIONS USAGE
sub <sub_name> (Arguments) { } Parameters passed to a subroutine can be accessed in a subroutine using a special variable @_ Package package_name; BEGIN { # initialization statement } Sub function_name { #body of function } Return 1; return $s END { #clean up statement } Save this file as package_name.pm use package_name; package_name::function_name();
proc sum args { set s 0 foreach i $args { incr s $i } sum 1 2 3 4 5 source ./scripname
EXTRAAS
catch {exec grep foo << $input | wc} error
217324234.xlsx.ms_office
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
STRING OPERATIONS
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.
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 join append 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" }
SCOPE OF VARIABLES
global uplevel upvar info rename trace my local
FILE HANDLING
open gets seek flush glob file close read tell cd pid puts source eof pwd open (FILE_HANDLE, EXPR ); EXPR = MODE + FILENAME open (FILEHANDLE, "<filename")
< - READ, > - WRITE, >> - APPEND <> - They instruct Perl to read one line of input from the file handle inside the operators.
% geography = (Bangalore , India , London, England); % geography = (Bangalore" => India", London" => England"); ($city, $country) = each %geography; @cities = keys %geography; @countries = values %geography;
REGULAR EXPRESSIONS
217324234.xlsx.ms_office
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 of characters 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);
217324234.xlsx.ms_office
PYTHON
python .py python filename.py, execfile('script.py') #!/usr/bin/python
os.system(command) or from datetime import date now = date.today() s=s+i print 'Hello world' OR print s
sys.stdin sys.stdout
217324234.xlsx.ms_office sys.stderr
for i in range(1,7):
217324234.xlsx.ms_office
if condition: action
217324234.xlsx.ms_office
sys.argv[0]
sys.argv
import module module.submodule.x OR from module import submodule submodule.x map(func,list), reduce(func,list), filter(func,list)
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()
217324234.xlsx.ms_office
hollow=hollow.replace('Shadow','Light') index=song.find('a')
TUPLE zoo = ('wolf', 'elephant', 'penguin') new_zoo = ('monkey', 'dolphin', zoo) len(new_zoo) new_zoo[2][2] --> penguin
217324234.xlsx.ms_office
DICTIONARY ab = { 'Swaroop' : 'swaroopch@byteofpython.info', 'Larry' : 'larry@wall.org', 'Matsumoto' : 'matz@ruby-lang.org', 'Spammer' : 'spammer@hotmail.com' } ab['Guido'] = 'guido@python.org' del ab['Spammer'] ab.items(): ab.has_key('Guido')
help()
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)