Talk Unix Shell Script

5,966 views

Published on

Published in: Technology, Education

Talk Unix Shell Script

  1. 1. UNIX Shell Script Dr. Tran, Van Hoai Faculty of Computer Science and Engineering HCMC Uni. of Technology [email_address]
  2. 2. What is a shell script? <ul><li>A series of OS commands for execution </li></ul><ul><li>Stored in a text file </li></ul>#!/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
  3. 3. Components of a script #!/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 Shell in use (sh, bash, csh) Comment Command
  4. 4. How to invoke a script <ul><li>Correct way </li></ul><ul><ul><li>$ /bin/bash my_script arg_1 arg_2 </li></ul></ul><ul><li>Simple way </li></ul><ul><ul><li>$ my_script arg_1 arg_2 </li></ul></ul><ul><li>The first line specifying the shell must be provided in simple way </li></ul>
  5. 5. How to be helped <ul><li>Man pages </li></ul><ul><ul><li>hoai@moon:~> man bash </li></ul></ul><ul><ul><li>... </li></ul></ul><ul><ul><li>hoai@moon:~> man sh </li></ul></ul><ul><ul><li>... </li></ul></ul>
  6. 6. Definitions <ul><li>Blank = chunk of tab or space </li></ul><ul><li>Name = sequence of ASCII letters , digits , underscores , beginning with a letter or underscore </li></ul><ul><li>Argument = string supplied on command-line </li></ul>
  7. 7. Example (argument) (1) <ul><li>#!/bin/sh </li></ul><ul><li>############################## </li></ul><ul><li>echo &quot;Script name is [$0]&quot; </li></ul><ul><li>echo &quot;First argument is [$1]&quot; </li></ul><ul><li>echo &quot;Second argument is [$2]&quot; </li></ul><ul><li>echo &quot;This process ID is [$$]&quot; </li></ul><ul><li>echo &quot;This argument count is [$#]&quot; </li></ul><ul><li>echo &quot;All arguments [$@]&quot; </li></ul>
  8. 8. Example (argument) (2) <ul><li>hoai@moon:~> my_script.sh hoai 1 university </li></ul><ul><li>Script name is [my_script.sh] </li></ul><ul><li>First argument is [hoai] </li></ul><ul><li>Second argument is [1] </li></ul><ul><li>This process ID is [5401] </li></ul><ul><li>This argument count is [3] </li></ul><ul><li>All arguments [hoai 1 university] </li></ul>
  9. 9. Filename metacharacters Current working directory ( $PWD ) ~+ Previous working directory ( $OLDPWD ) ~- Home directory of user name ~ name Home directory of the current user ~ Match any character not enclosed as above [! 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 single character ? Match any string of zero or more characters *
  10. 10. Simple regular expressions (Korn shell) <ul><li>Pattern = sequence of patterns separated by “|” </li></ul>Match any strings that don't match pattern !( pattern ) Match exactly one instance of pattern @( pattern ) Match one or more instances of pattern +( pattern ) Match zero or more instances of pattern *( pattern ) Match zero or one instance of pattern ?( pattern )
  11. 11. Example (metacharacters) <ul><li>List files having prefix new </li></ul><ul><ul><li>$ ls new* </li></ul></ul><ul><li>Cat files having prefix ch and one more letter </li></ul><ul><ul><li>$ cat ch? </li></ul></ul><ul><li>Vi files starting by letters from D to E </li></ul><ul><ul><li>$ vi [D-R]* </li></ul></ul><ul><li>Print files not *.o and core (Korn shell) </li></ul><ul><ul><li>$ pr !(*.o|core) | lp </li></ul></ul>
  12. 12. Quoting Charater following taken literally Everything taken literally '' <ul><li>Everything taken literally, except </li></ul><ul><li>$ (variable substitution) </li></ul><ul><li>` (command substitution) </li></ul><ul><li>“ (ending mark) </li></ul>&quot;&quot;
  13. 13. Example (quoting) <ul><li>$ echo 'my class is &quot;unix and tools&quot;' </li></ul><ul><li>My class is &quot;unix and tools&quot; </li></ul><ul><li>$ echo &quot;Well, isn't that &quot;good&quot; ?&quot; </li></ul><ul><li>Well, isn't that &quot;good&quot; ? </li></ul><ul><li>$ echo &quot;You have `ls | wc –l` files in `pwd`&quot; </li></ul><ul><li>You have 34 files in /home/hoai </li></ul><ul><li>$ echo &quot;The value of $x is $x&quot; </li></ul><ul><li>The value of $x is 100 </li></ul>
  14. 14. Variables (1) Use var if set, otherwise, print value and exit ${ var :? value } Use value of var is set, otherwise use nothing ${ var :+ value } Use the length of var ${# var } Use the number of positional arguments ${#*} or ${#@} Use var if set, otherwise, user value and assign it to var ${ var := value } Use var if set, otherwise, use value ${ var :- value } Use value of var ${ var } Set variable to value var=value …
  15. 15. Variables (2) Same as # pattern . Remove longest 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 } Use value of var after removing pattern from the left. Remove shortest matching ${ var # pattern }
  16. 16. Command forms OR cmd1 || cmd2 AND; cmd1, then cmd2 if (cmd succeeds) cmd1 && cmd2 POSIX shell arithmetic substitution cmd $((expression)) POSIX Command substitution (nesting is allowed) cmd1 $(cmd2) Command substitution cmd1 `cmd2` Pipe cmd1 | cmd2 NOT; change exit status ! cmd Commands as a group in a subshell ( cmd1 ; cmd2 ) Commands as a group in current shell { cmd1 ; cmd2 } Multiple commands on the same line cmd1 ; cmd2
  17. 17. Example (command forms) <ul><li>$ nroff file > file.txt & </li></ul><ul><li>Format in the background </li></ul><ul><li>$ cd; ls </li></ul><ul><li>Execute sequentially </li></ul><ul><li>$ (date; who; pwd) > logfile </li></ul><ul><li>All output is redirected </li></ul><ul><li>$ sort file | pr -3 | lp </li></ul><ul><li>Sort file, page output, then print </li></ul><ul><li>$ vi 'grep -l ifdef *.c' </li></ul><ul><li>Edit files found by grep </li></ul><ul><li>$ grep XX file && lp file </li></ul><ul><li>Print file if it contains the pattern; </li></ul><ul><li>$ grep XX file || echo &quot;XX not found&quot; </li></ul><ul><li>otherwise, echo an error message </li></ul>
  18. 18. Simple commands Create date strings date Evaluate variables eval Transform characters tr 'a' 'b' Simple arithmetic processor expr Predicate or conditional processor [( test )] Access lines in files head/tail Chop up a text by strings or characters cut Get directory name from path string dirname Get file name from path string basename Search for regular expressions grep Sort lines sort
  19. 19. Example (script) (1) <ul><li>#!/bin/bash </li></ul><ul><li>alphabet=&quot;a b c d e&quot; # Initialise a string </li></ul><ul><li>count=0 # Initialise a counter </li></ul><ul><li>for letter in $alphabet # Set up a loop control </li></ul><ul><li>do # Begin the loop </li></ul><ul><li>count=`expr $count + 1` # Increment the counter </li></ul><ul><li># Display the result </li></ul><ul><li>echo &quot;Letter $count is [$letter]&quot; </li></ul><ul><li>done </li></ul>
  20. 20. Example (script) (2) <ul><li>alphabet=&quot;a b c d e&quot; # Initialise a string </li></ul><ul><li>count=0 # Initialise a counter </li></ul><ul><li>while [ $count -lt 5 ] # Set up a loop control </li></ul><ul><li>do # Begin the loop </li></ul><ul><li>count=`expr $count + 1` # Increment the counter </li></ul><ul><li># Position of next letter </li></ul><ul><li>position=`bc $count + $count - 1` </li></ul><ul><li>letter=`echo &quot;$alphabet&quot; | cut -c$position-$position` # Get next letter </li></ul><ul><li># Display the result </li></ul><ul><li>echo &quot;Letter $count is [$letter]&quot; </li></ul><ul><li>done </li></ul>
  21. 21. Homeworks (1) <ul><li>Write a script for C compiler </li></ul><ul><ul><li>Objective: use gcc by default, if gcc is not availablle, find another compiler (ending with cc ) instead. </li></ul></ul><ul><li>Write a script to convert filenames to lowercase letters </li></ul><ul><ul><li>Input: a directory path string </li></ul></ul><ul><ul><li>Output: all filenames in the directory in lowercase </li></ul></ul>
  22. 22. Homeworks (2) <ul><li>Write a script to warn users using too much space </li></ul><ul><ul><li>Objective: find all users of the system (/etc/passwd, cut), check if someone uses > 1GB, mail him a warning message </li></ul></ul>
  23. 23. <ul><li>Conditional structure </li></ul><ul><li>Loop structure </li></ul><ul><li>Function </li></ul><ul><li>File input/output </li></ul><ul><li>Array </li></ul>are NEXT

×