SlideShare a Scribd company logo
UNIX Shell Script (1) Dr. Tran, Van Hoai Faculty of Computer Science and Engineering HCMC Uni. of Technology [email_address]
What is a shell script? A  series  of OS commands for execution Stored in a  text  file #!/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
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
How to invoke a script Correct way $ /bin/bash my_script arg_1 arg_2 Simple way $ my_script arg_1 arg_2 The first line specifying the shell  must be provided  in simple way
How to be helped Man pages hoai@moon:~>  man bash ... hoai@moon:~>  man sh ...
Definitions Blank = chunk of  tab  or  space Name = sequence of  ASCII letters ,  digits ,  underscores ,  beginning with a letter or underscore Argument = string supplied on command-line
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   [$@]"
Example (argument) (2) hoai@moon:~>  my_script.sh hoai 1 university Script name is   [my_script.sh] First argument is  [hoai] Second argument is  [1] This process ID is  [5401] This argument count is  [3] All arguments  [hoai 1 university]
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 *
Simple regular expressions (Korn shell) Pattern = sequence of patterns  separated by “|” 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 )
Example (metacharacters) 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
Quoting Charater following  \  taken literally \ Everything taken literally '' Everything taken literally, except $  (variable substitution) `  (command substitution) “   (ending mark) ""
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/hoai $ echo "The value of \$x is $x" The value of $x is 100
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 …
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 }
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
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
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
Example (script) (1) #!/bin/bash alphabet="a b c d e"   # Initialise a string count=0  # Initialise 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
Example (script) (2) alphabet="a b c d e"  # Initialise a string count=0  # Initialise 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-$position`  # Get next letter  # Display the result  echo "Letter $count is [$letter]" done
Homeworks (1) Write a script for C compiler Objective: use  gcc  by default, if  gcc  is not availablle, find another compiler (ending with  cc ) instead. Write a script to convert filenames to lowercase letters Input: a directory path string Output: all filenames in the directory in lowercase
Homeworks (2) Write a script to warn users using too much space Objective: find all users of the system (/etc/passwd, cut), check if someone uses > 1GB, mail him a warning message
Conditional structure Loop structure Function File input/output Array are  NEXT

More Related Content

PPT
Airlover 20030324 1
PPT
Talk Unix Shell Script
PPT
Using Unix
PPT
Unix And C
PPT
Unix Basics
PDF
Unix Commands
PPTX
Bash Shell Scripting
PPTX
Unix shell scripting basics
Airlover 20030324 1
Talk Unix Shell Script
Using Unix
Unix And C
Unix Basics
Unix Commands
Bash Shell Scripting
Unix shell scripting basics

What's hot (20)

PDF
Introduction to Bash Scripting, Zyxware Technologies, CSI Students Convention...
PDF
Shell scripting
PDF
Introduction to shell scripting
PPT
Chap06
PPT
Unix Shell Scripting Basics
PPT
Shell Scripting
PDF
Quick start bash script
PPT
Unix Shell Scripting Basics
PPT
Unix And Shell Scripting
PPT
Shell Scripts
RTF
Unix lab manual
PPTX
Unix - Shell Scripts
PDF
Unix 1st sem lab programs a - VTU Karnataka
PPT
Bash shell
PPTX
Bash Shell Scripting
PPTX
Unix shell scripting
PDF
Shell scripting
PPTX
First steps in C-Shell
PPTX
Unix shell scripts
PDF
COSCUP2012: How to write a bash script like the python?
Introduction to Bash Scripting, Zyxware Technologies, CSI Students Convention...
Shell scripting
Introduction to shell scripting
Chap06
Unix Shell Scripting Basics
Shell Scripting
Quick start bash script
Unix Shell Scripting Basics
Unix And Shell Scripting
Shell Scripts
Unix lab manual
Unix - Shell Scripts
Unix 1st sem lab programs a - VTU Karnataka
Bash shell
Bash Shell Scripting
Unix shell scripting
Shell scripting
First steps in C-Shell
Unix shell scripts
COSCUP2012: How to write a bash script like the python?
Ad

Similar to Talk Unix Shell Script 1 (20)

PPT
ShellAdvanced aaäaaaaaaaaaaaaaaaaaaaaaaaaaaa
PPT
ShellAdvanced shell scripting programm.ppt
PPTX
shellScriptAlt.pptx
PPT
Perl Presentation
PPT
PPT
Shell programming
PDF
Bioinformatica: Esercizi su Perl, espressioni regolari e altre amenità (BMR G...
PPT
You Can Do It! Start Using Perl to Handle Your Voyager Needs
PPT
Bioinformatica 29-09-2011-p1-introduction
PPTX
KT on Bash Script.pptx
PDF
Unix Tutorial
PPTX
Lecture 3 Perl & FreeBSD administration
PDF
Module 03 Programming on Linux
PDF
Scripting and the shell in LINUX
PPT
390aLecture05_12sp.ppt
ODP
Introduction to Perl
ODP
Introduction to Perl - Day 1
PPTX
Perl courseparti
PPT
34-shell-programming.ppt
PPSX
Php and MySQL
ShellAdvanced aaäaaaaaaaaaaaaaaaaaaaaaaaaaaa
ShellAdvanced shell scripting programm.ppt
shellScriptAlt.pptx
Perl Presentation
Shell programming
Bioinformatica: Esercizi su Perl, espressioni regolari e altre amenità (BMR G...
You Can Do It! Start Using Perl to Handle Your Voyager Needs
Bioinformatica 29-09-2011-p1-introduction
KT on Bash Script.pptx
Unix Tutorial
Lecture 3 Perl & FreeBSD administration
Module 03 Programming on Linux
Scripting and the shell in LINUX
390aLecture05_12sp.ppt
Introduction to Perl
Introduction to Perl - Day 1
Perl courseparti
34-shell-programming.ppt
Php and MySQL
Ad

More from Dr.Ravi (18)

PDF
Corporate Overview
PDF
Excel For The Ceo
PDF
Project Specs Pf
PDF
Pf Day5
PDF
Assignments Programming Fundamentals
PDF
Hdd Chssc
PDF
Chssc Day3
PDF
Chssc Day1
PDF
Pf Day3
PDF
Ldd Pf
PDF
Chssc Assignments
PDF
Chssc Day4
PDF
Chssc Day2
PPT
Unix Lec2
PDF
Unix Book
PPT
Unix Basics 04sp
PDF
Wicked Cool Shell Scripts
PPT
SAP INTRO
Corporate Overview
Excel For The Ceo
Project Specs Pf
Pf Day5
Assignments Programming Fundamentals
Hdd Chssc
Chssc Day3
Chssc Day1
Pf Day3
Ldd Pf
Chssc Assignments
Chssc Day4
Chssc Day2
Unix Lec2
Unix Book
Unix Basics 04sp
Wicked Cool Shell Scripts
SAP INTRO

Recently uploaded (20)

PPTX
MYSQL Presentation for SQL database connectivity
PPTX
A Presentation on Artificial Intelligence
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
Unlocking AI with Model Context Protocol (MCP)
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PPTX
Cloud computing and distributed systems.
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Machine learning based COVID-19 study performance prediction
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
MYSQL Presentation for SQL database connectivity
A Presentation on Artificial Intelligence
Agricultural_Statistics_at_a_Glance_2022_0.pdf
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Unlocking AI with Model Context Protocol (MCP)
20250228 LYD VKU AI Blended-Learning.pptx
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
The Rise and Fall of 3GPP – Time for a Sabbatical?
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Building Integrated photovoltaic BIPV_UPV.pdf
Cloud computing and distributed systems.
Network Security Unit 5.pdf for BCA BBA.
Advanced methodologies resolving dimensionality complications for autism neur...
Encapsulation_ Review paper, used for researhc scholars
Machine learning based COVID-19 study performance prediction
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
Understanding_Digital_Forensics_Presentation.pptx
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Digital-Transformation-Roadmap-for-Companies.pptx

Talk Unix Shell Script 1

  • 1. UNIX Shell Script (1) Dr. Tran, Van Hoai Faculty of Computer Science and Engineering HCMC Uni. of Technology [email_address]
  • 2. What is a shell script? A series of OS commands for execution Stored in a text file #!/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. 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. How to invoke a script Correct way $ /bin/bash my_script arg_1 arg_2 Simple way $ my_script arg_1 arg_2 The first line specifying the shell must be provided in simple way
  • 5. How to be helped Man pages hoai@moon:~> man bash ... hoai@moon:~> man sh ...
  • 6. Definitions Blank = chunk of tab or space Name = sequence of ASCII letters , digits , underscores , beginning with a letter or underscore Argument = string supplied on command-line
  • 7. 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 [$@]"
  • 8. Example (argument) (2) hoai@moon:~> my_script.sh hoai 1 university Script name is [my_script.sh] First argument is [hoai] Second argument is [1] This process ID is [5401] This argument count is [3] All arguments [hoai 1 university]
  • 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. Simple regular expressions (Korn shell) Pattern = sequence of patterns separated by “|” 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. Example (metacharacters) 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
  • 12. Quoting Charater following \ taken literally \ Everything taken literally '' Everything taken literally, except $ (variable substitution) ` (command substitution) “ (ending mark) ""
  • 13. 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/hoai $ echo "The value of \$x is $x" The value of $x is 100
  • 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. 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. 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. 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
  • 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. Example (script) (1) #!/bin/bash alphabet="a b c d e" # Initialise a string count=0 # Initialise 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
  • 20. Example (script) (2) alphabet="a b c d e" # Initialise a string count=0 # Initialise 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-$position` # Get next letter # Display the result echo "Letter $count is [$letter]" done
  • 21. Homeworks (1) Write a script for C compiler Objective: use gcc by default, if gcc is not availablle, find another compiler (ending with cc ) instead. Write a script to convert filenames to lowercase letters Input: a directory path string Output: all filenames in the directory in lowercase
  • 22. Homeworks (2) Write a script to warn users using too much space Objective: find all users of the system (/etc/passwd, cut), check if someone uses > 1GB, mail him a warning message
  • 23. Conditional structure Loop structure Function File input/output Array are NEXT