Shell Script Examples 1 A shell script is





![Example (argument) (1) #!/bin/sh ############### echo "Script name is [$0]" echo "First argument is Example (argument) (1) #!/bin/sh ############### echo "Script name is [$0]" echo "First argument is](https://slidetodoc.com/presentation_image_h2/86466db750cd12a55694a3f03e5c1698/image-6.jpg)













- Slides: 19

Shell Script Examples 1

A shell script is… A series of OS commands for execution n Stored in a text file n #!/bin/sh rm -f /tmp/listing. tmp > /dev/null 2>&1 touch /tmp/listing. tmp ls -l [a-z]*. doc | sort > /tmp/listing. tmp lpr -Ppostscript_1 /tmp/listing. tmp rm -f /tmp/listing. tmp 2

Components of a script Shell in use (sh, bash, csh) #!/bin/sh rm -f /tmp/listing. tmp > /dev/null 2>&1 touch /tmp/listing. tmp # This is a comment ls -l [a-z]*. doc | sort > /tmp/listing. tmp lpr -Ppostscript_1 /tmp/listing. tmp rm -f /tmp/listing. tmp Command Comment 3

How to invoke a script n Correct way $ /bin/bash my_script arg_1 arg_2 n Simple way $ my_script arg_1 arg_2 n The first line specifying the shell must be provided in simple way 4

Definitions Blank = chunk of tab or space n Name = sequence of ASCII letters, digits, underscores, beginning with a letter or underscore n Argument = string supplied on commandline n 5
![Example argument 1 binsh echo Script name is 0 echo First argument is Example (argument) (1) #!/bin/sh ############### echo "Script name is [$0]" echo "First argument is](https://slidetodoc.com/presentation_image_h2/86466db750cd12a55694a3f03e5c1698/image-6.jpg)
Example (argument) (1) #!/bin/sh ############### echo "Script name is [$0]" echo "First argument is [$1]" echo "Second argument is [$2]" echo "This process ID is [$$]" echo "This argument count is [$#]" echo "All arguments [$@]" 6

Example (argument) (2) : ~> my_script. sh bhecker 1 university Script name is [my_script. sh] First argument is [bhecker] Second argument is [1] This process ID is [5401] This argument count is [3] All arguments [bhecker 1 university] 7

Filename meta characters * Match any string of zero or more characters ? Match any single character [abc. . . ] Match any one of the enclosed characters; a hyphen can specify a range (e. g. , a-z, A-Z, 0– 9) [!abc. . . ] Match any character not enclosed as above ~ Home directory of the current user ~name Home directory of user name ~+ Current working directory ($PWD) ~- Previous working directory ($OLDPWD) 8

Simple regular expressions (Korn shell) ? (pattern) Match zero or one instance of pattern *(pattern) Match zero or more instances of pattern +(pattern) Match one or more instances of pattern @(pattern) Match exactly one instance of pattern !(pattern) Match any strings that don't match pattern n Pattern = sequence of patterns separated by “|” 9

Example (meta characters) List files having prefix new $ ls new* Cat files having prefix ch and one more letter $ cat ch? Vi files starting by letters from D to E $ vi [D-R]* Print files not *. o and core (Korn shell) $ pr !(*. o|core) | lp 10

Quoting "" Everything taken literally, except $ (variable substitution) n ` (command substitution) n “ (ending mark) n '' Everything taken literally Character following taken literally 11

Example (quoting) $ echo 'my class is "unix and tools"' My class is "unix and tools" $ echo "Well, isn't that "good" ? " Well, isn't that "good" ? $ echo "You have `ls | wc –l` files in `pwd`" You have 34 files in /home/bhecker $ echo "The value of $x is $x" The value of $x is 100 12

Variables (1) var=value… ${var} Set variable to value Use value of var ${var: -value} Use var if set, otherwise, use value ${var: =value} Use var if set, otherwise, user value and assign it to var ${var: ? value} Use var if set, otherwise, print value and exit ${var: +value} Use value of var is set, otherwise use nothing ${#var} Use the length of var ${#*} or ${#@} Use the number of positional arguments 13

Variables (2) Use value of var after removing pattern from the left. Remove shortest matching ${var##pattern} Same as #pattern. Remove longest matching ${var#pattern} Use value of var after removing pattern from the right. Remove shortest matching ${var%%pattern} Same as %pattern. Remove longest matching ${var%pattern} 14

Command forms cmd 1 ; cmd 2 Multiple commands on the same line {cmd 1 ; cmd 2} Commands as a group in current shell (cmd 1 ; cmd 2) Commands as a group in a subshell cmd 1 | cmd 2 Pipe cmd 1 `cmd 2` Command substitution cmd 1 $(cmd 2) POSIX Command substitution (nesting is allowed) cmd POSIX shell arithmetic substitution $((expression)) cmd 1 && cmd 2 AND; cmd 1, then cmd 2 if (cmd succeeds) cmd 1 || cmd 2 OR ! cmd NOT; change exit status 15

Example (command forms) $ nroff file > file. txt & Format in the background $ cd; ls Execute sequentially $ (date; who; pwd) > logfile All output is redirected $ sort file | pr -3 | lp Sort file, page output, then print $ vi 'grep -l ifdef *. c' Edit files found by grep $ grep XX file && lp file Print file if it contains the pattern; $ grep XX file || echo "XX not found" otherwise, echo an error message 16

Simple commands sort Sort lines grep Search for regular expressions basename Get file name from path string dirname Get directory name from path string cut Chop up a text by strings or characters [(test)] Predicate or conditional processor tr 'a' 'b' Transform characters expr Simple arithmetic processor eval Evaluate variables date Create date strings head/tail Access lines in files 17

Example (script) (1) #!/bin/bash alphabet="a b c d e" # Initialize a string count=0 # Initialize a counter for letter in $alphabet # Set up a loop control do # Begin the loop count=‘expr $count + 1’ # Increment the counter # Display the result echo "Letter $count is [$letter]" done 18

Example (script) (2) alphabet="a b c d e" # Initialize a string count=0 # Initialize a counter while [ $count -lt 5 ] # Set up a loop control do # Begin the loop count=‘expr $count + 1’ # Increment the counter # Position of next letter position=‘bc $count + $count – 1’ letter=‘echo "$alphabet" | cut -c$position’ # Get next letter # Display the result echo "Letter $count is [$letter]" done 19