<<

Shell Information $? = status of previous

#!/bin/bash read varName first line of sets value of variable varName to next line read from stdin command > filename output to filename ’str ’ = str "str " = str with variables interpolated command >> file ‘command ‘ = output of command as string append output to filename Zero means true/successful command 2> filename Non-zero exit status means false/failure write stderr to filename expression command >file 2>&1 returns expression result as exit sta- write stdout and stderr to filenametus integer operators: -lt,-gt,-eq,-ne,-ge,-le

command1 | command2 exit Number pipe output from command1 terminate script with exit status Number as input to command2 if Commanda ; then command1 && command2 Commands1 execute command2 if command1 elif Commandb ; then has exit status zero Commands2 else command1 || command2 Commands3; execute command2 if command1 fi does not have exit status zero case Word in $((expression )) Pattern1) Commands1 ;; expression evaluated as arithmeticPattern2) Commands2 ;; ... $0 = name of currently executing command *) Commandsn ;; $1,$2,$3,... = command-line arguments esac $# = count of command-line arguments

1 while Command ; do . () Commands matches any single character done (pattern ) matches pattern for var in Word1 Word2 ... do Anchors: Commands done ^pattern matches pattern the start of a line # Display lines from file pattern $ count=0 matches pattern at the end of a line while read line do Selection: count=$((count + 1)) "Line $count: $line" [charList ] done

Regular Expressions Repetition:

Atomic Patterns: pattern ? zero or one occurrences of pattern letters, digits, punctuation (except those be- pattern * low) zero or occurrences of pattern match any occurrence of themselves pattern + \. \* \+ \? \| \^ \$ \[ \] one or more occurrences of pattern match any occurrence of the second char- acter \ matches alphanumeric, including ’_’

2 \s matches whitespace Perl Information \d matches numeric #!/usr/bin/perl -w - first line of file \b word boundary $var - simple scalar variable pattern {N ,M } $var[n ]- n th element of array matches N to M occur- $var{val }- ele- rences of pattern ment of for key val @var - entire array, or length in scalar context @var[i,j,k ]- slice from array %var - entire hash

’str ’ = str "str " = str with variables interpolated ‘command ‘ = output of command as string

empty string and numeric zero are FALSE anything else is TRUE

$_ - default input or matched pattern $0 - name of the Perl script file $? - exit status of last system command $$ - process id of Perl runtime process @ARGV - command line arguments % - environment variables %INC - path for included scripts

Arithmetic operators: + - * / ** (power) % (mod) .. (range)

Relational operators: == != < > <= >= (nu- meric) eq ne lt gt le ge (string) =~ !~ (pat- tern)

Logical operators:

3 ! (NOT) && (AND) || (OR) (any of &, (, ) can be omitted) not and or (low-precedence ver- sions) sub name block - subroutine definition Bitwise operators: - in block, @_ holds args ~ (NOT) & (AND) | (OR) ^ (XOR)

String operations: Arithmetic: . concatenation abs expr x repetition returns absolute value of expr sin, cos, atan2 expr $var = expression ; returns geometric function on expr $var ++; ++$var ; int expr $var += expr ; $var -= expr ; ... returns integer portion of expr $var =~ s/pattern /replacement /; rand [ expr ] $var =~ /chars /chars /; returns random value in 0..expr returns random in 0..1 if no expr sqrt expr block = { statement1; statement2; ... } returns square root of expr while (condition ) block returns # seconds since Jan 1 1970 until (condition ) block do block while (condition ) Conversions: do block until (condition ) chr expr for (init ;test ;next ) block returns char represented by expr foreach $var (list ) block localtime expr converts expr into a date/time string last - exit the loop ord expr next - go to next iteration returns ascii for first char in expr redo - restart this iteration : if (condition1) block1 chomp list elsif (condition2) block2 removes line end- ... ings from each string in list elsif (conditionn) blockn chop list else blockn+1 removes last char from each string in list index str ,substr [,offset ] &subroutine (arglist ); returns position of substr in str (or -1)

4 and starts looking from offset, if given ues of list onto end of array length str reverse list returns # characters in str returns the list in reverse order lc str shift @array uc str pops off and returns first ele- returns lower/upper case version of str ment from array lcfirst str [block |subr ] list ucfirst str returns a sorted array of val- returns str with 1st char in lower/upper caseues from list substr str ,offset [,len ] block /subr can be used to define order- returns substring of str start- ing ing at offset /pattern /,string extending to end (or len chars, if sup- split string at pattern s (de- plied) fault \s) returns an array of split fragments Arrays: unshift @array ,list delete $hash {key } pushes val- remove key and its value from hash ues of list onto front of array expr ,list grep block ,list Files/Directories: returns array of all elements from list Tests (argument is either filename or filehandle) for expr /block evaluates to true -r -w -x - file is read/write/executable expr ,list -e -z - file exists, has zero size returns a string containing all elements -s - file size in bytes from list , separated by expr -M - time since file modified keys %hash -f -d - file is plain file, directory values %hash list returns an - change permissions of files in list ray of all keys/values in hash first list element must be numeri- map expr ,list mode map block ,list oldfile ,newfile evaluates expr /block for each element symlink oldfile ,newfile of list and returns array of results creates a link/symlink pop @array ,mode pops off and returns last ele- dirname ment from array create/remove directory dirname push @array ,list list , pushes val- remove all files named in list

5 System interation: Input/Output: chdir expr Changes working directory to expr in scalar con- die expr text, read next line from handle print value of expr to STDERR and exit in array con- exit expr text, read all lines from handle terminate with exit status expr <> expr reads from in- suspend program execution for expr secs put stream made from all files system expr specified in @ARGV or else from STDIN execute expr as a Unix command close handle closes the file/pipe associ- CGI.pm ated with handle header() flock handle ,op return HTTP header performs file-locking opera- param() tion on handle list of parameters op is a combination of 1(shared), param(name ) 2(exclusive), 4(non-block), 8(unlock) value of parameter name getc handle param(name , value ) returns next character from handle set parameter name to value open handle ,filename start_html, end_html opens a file and asso- start_form, end_form ciates it with handle textfield, textarea, submit, hidden conventions for specifying filename : short cuts to produce HTML "file " open file for out- put and truncate ">>file " open file for appending "|cmd " open pipe to write to cmd "cmd |" open pipe to read from cmd print [handle ] expr displays expr on handle (STDOUT) stream [handle ] ,list formats list using fmt and displays

6