SlideShare a Scribd company logo
UNIX Shell Script 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
Talk Unix Shell Script 1
Dr.Ravi
 
PPT
Airlover 20030324 1
Dr.Ravi
 
PPT
Unix Basics
Dr.Ravi
 
PPT
Using Unix
Dr.Ravi
 
PPT
Unix And C
Dr.Ravi
 
PDF
Unix Commands
Dr.Ravi
 
PPTX
Unix shell scripting basics
Manav Prasad
 
PDF
Introduction to Bash Scripting, Zyxware Technologies, CSI Students Convention...
Zyxware Technologies
 
Talk Unix Shell Script 1
Dr.Ravi
 
Airlover 20030324 1
Dr.Ravi
 
Unix Basics
Dr.Ravi
 
Using Unix
Dr.Ravi
 
Unix And C
Dr.Ravi
 
Unix Commands
Dr.Ravi
 
Unix shell scripting basics
Manav Prasad
 
Introduction to Bash Scripting, Zyxware Technologies, CSI Students Convention...
Zyxware Technologies
 

What's hot (20)

PPTX
Bash Shell Scripting
Raghu nath
 
PDF
Introduction to shell scripting
Corrado Santoro
 
PPT
Unix Shell Scripting Basics
Sudharsan S
 
PDF
Shell scripting
Manav Prasad
 
PPT
Shell Scripting
Gaurav Shinde
 
PPT
Chap06
Dr.Ravi
 
PPT
Unix Shell Scripting Basics
Dr.Ravi
 
PPT
Unix And Shell Scripting
Jaibeer Malik
 
PDF
Quick start bash script
Simon Su
 
PPTX
Unix shell scripting
Pavan Devarakonda
 
PPT
Shell Scripts
Dr.Ravi
 
PPT
Bash shell
xylas121
 
PDF
Shell scripting
Ashrith Mekala
 
PPTX
Unix - Shell Scripts
ananthimurugesan
 
PPTX
Bash Shell Scripting
Raghu nath
 
PDF
Shell scripting
Geeks Anonymes
 
PDF
COSCUP2012: How to write a bash script like the python?
Lloyd Huang
 
PDF
Scripting and the shell in LINUX
Bhushan Pawar -Java Trainer
 
RTF
Unix lab manual
Chaitanya Kn
 
PPTX
Easiest way to start with Shell scripting
Akshay Siwal
 
Bash Shell Scripting
Raghu nath
 
Introduction to shell scripting
Corrado Santoro
 
Unix Shell Scripting Basics
Sudharsan S
 
Shell scripting
Manav Prasad
 
Shell Scripting
Gaurav Shinde
 
Chap06
Dr.Ravi
 
Unix Shell Scripting Basics
Dr.Ravi
 
Unix And Shell Scripting
Jaibeer Malik
 
Quick start bash script
Simon Su
 
Unix shell scripting
Pavan Devarakonda
 
Shell Scripts
Dr.Ravi
 
Bash shell
xylas121
 
Shell scripting
Ashrith Mekala
 
Unix - Shell Scripts
ananthimurugesan
 
Bash Shell Scripting
Raghu nath
 
Shell scripting
Geeks Anonymes
 
COSCUP2012: How to write a bash script like the python?
Lloyd Huang
 
Scripting and the shell in LINUX
Bhushan Pawar -Java Trainer
 
Unix lab manual
Chaitanya Kn
 
Easiest way to start with Shell scripting
Akshay Siwal
 
Ad

Viewers also liked (8)

ODP
Shellprogramming
Andrew Vandever
 
PDF
Bash Beginners Guide
Dinesh Vasudevan
 
PPT
Purpose of command interpreter
Sumant Diwakar
 
PDF
operating system structure
Waseem Ud Din Farooqui
 
PDF
SysProg-Tutor 02 Introduction to Unix Operating System
Wongyos Keardsri
 
PPTX
UNIX Operating System
Unless Yuriko
 
PPTX
Unix Operating System
subhsikha
 
PPTX
Unix operating system
ABhay Panchal
 
Shellprogramming
Andrew Vandever
 
Bash Beginners Guide
Dinesh Vasudevan
 
Purpose of command interpreter
Sumant Diwakar
 
operating system structure
Waseem Ud Din Farooqui
 
SysProg-Tutor 02 Introduction to Unix Operating System
Wongyos Keardsri
 
UNIX Operating System
Unless Yuriko
 
Unix Operating System
subhsikha
 
Unix operating system
ABhay Panchal
 
Ad

Similar to Talk Unix Shell Script (20)

PPTX
First steps in C-Shell
Brahma Killampalli
 
PPT
ShellAdvanced aaäaaaaaaaaaaaaaaaaaaaaaaaaaaa
ewout2
 
PPT
ShellAdvanced shell scripting programm.ppt
ubaidullah75790
 
PPT
Perl Presentation
Sopan Shewale
 
PPTX
shellScriptAlt.pptx
NiladriDey18
 
PPT
Unix
nazeer pasha
 
PPT
Shell programming
Moayad Moawiah
 
PPT
You Can Do It! Start Using Perl to Handle Your Voyager Needs
Roy Zimmer
 
PDF
Bioinformatica: Esercizi su Perl, espressioni regolari e altre amenitĂ  (BMR G...
Andrea Telatin
 
PDF
Module 03 Programming on Linux
Tushar B Kute
 
PPTX
Lecture 3 Perl & FreeBSD administration
Mohammed Farrag
 
PPTX
KT on Bash Script.pptx
gogulasivannarayana
 
ODP
Introduction to Perl
Dave Cross
 
PPT
Bioinformatica 29-09-2011-p1-introduction
Prof. Wim Van Criekinge
 
ODP
Introduction to Perl - Day 1
Dave Cross
 
PDF
Unix Tutorial
Sanjay Saluth
 
PPTX
Perl courseparti
ernlow
 
PPT
Introduction to Perl
NBACriteria2SICET
 
PPT
390aLecture05_12sp.ppt
mugeshmsd5
 
PPTX
Linux Shell Scripting
Raghu nath
 
First steps in C-Shell
Brahma Killampalli
 
ShellAdvanced aaäaaaaaaaaaaaaaaaaaaaaaaaaaaa
ewout2
 
ShellAdvanced shell scripting programm.ppt
ubaidullah75790
 
Perl Presentation
Sopan Shewale
 
shellScriptAlt.pptx
NiladriDey18
 
Unix
nazeer pasha
 
Shell programming
Moayad Moawiah
 
You Can Do It! Start Using Perl to Handle Your Voyager Needs
Roy Zimmer
 
Bioinformatica: Esercizi su Perl, espressioni regolari e altre amenitĂ  (BMR G...
Andrea Telatin
 
Module 03 Programming on Linux
Tushar B Kute
 
Lecture 3 Perl & FreeBSD administration
Mohammed Farrag
 
KT on Bash Script.pptx
gogulasivannarayana
 
Introduction to Perl
Dave Cross
 
Bioinformatica 29-09-2011-p1-introduction
Prof. Wim Van Criekinge
 
Introduction to Perl - Day 1
Dave Cross
 
Unix Tutorial
Sanjay Saluth
 
Perl courseparti
ernlow
 
Introduction to Perl
NBACriteria2SICET
 
390aLecture05_12sp.ppt
mugeshmsd5
 
Linux Shell Scripting
Raghu nath
 

More from Dr.Ravi (18)

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

Recently uploaded (20)

PDF
How Onsite IT Support Drives Business Efficiency, Security, and Growth.pdf
Captain IT
 
PPTX
Smart Infrastructure and Automation through IoT Sensors
Rejig Digital
 
PDF
Why Your AI & Cybersecurity Hiring Still Misses the Mark in 2025
Virtual Employee Pvt. Ltd.
 
PDF
How-Cloud-Computing-Impacts-Businesses-in-2025-and-Beyond.pdf
Artjoker Software Development Company
 
PDF
Oracle AI Vector Search- Getting Started and what's new in 2025- AIOUG Yatra ...
Sandesh Rao
 
PDF
NewMind AI Monthly Chronicles - July 2025
NewMind AI
 
PDF
A Day in the Life of Location Data - Turning Where into How.pdf
Precisely
 
PDF
Automating ArcGIS Content Discovery with FME: A Real World Use Case
Safe Software
 
PDF
CIFDAQ'S Market Insight: BTC to ETH money in motion
CIFDAQ
 
PDF
Chapter 2 Digital Image Fundamentals.pdf
Getnet Tigabie Askale -(GM)
 
PDF
BLW VOCATIONAL TRAINING SUMMER INTERNSHIP REPORT
codernjn73
 
PDF
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
PDF
madgavkar20181017ppt McKinsey Presentation.pdf
georgschmitzdoerner
 
PDF
agentic-ai-and-the-future-of-autonomous-systems.pdf
siddharthnetsavvies
 
PDF
Make GenAI investments go further with the Dell AI Factory - Infographic
Principled Technologies
 
PPTX
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
sujalchauhan1305
 
PPTX
C Programming Basics concept krnppt.pptx
Karan Prajapat
 
PDF
The Evolution of KM Roles (Presented at Knowledge Summit Dublin 2025)
Enterprise Knowledge
 
PDF
NewMind AI Weekly Chronicles - July'25 - Week IV
NewMind AI
 
PDF
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Principled Technologies
 
How Onsite IT Support Drives Business Efficiency, Security, and Growth.pdf
Captain IT
 
Smart Infrastructure and Automation through IoT Sensors
Rejig Digital
 
Why Your AI & Cybersecurity Hiring Still Misses the Mark in 2025
Virtual Employee Pvt. Ltd.
 
How-Cloud-Computing-Impacts-Businesses-in-2025-and-Beyond.pdf
Artjoker Software Development Company
 
Oracle AI Vector Search- Getting Started and what's new in 2025- AIOUG Yatra ...
Sandesh Rao
 
NewMind AI Monthly Chronicles - July 2025
NewMind AI
 
A Day in the Life of Location Data - Turning Where into How.pdf
Precisely
 
Automating ArcGIS Content Discovery with FME: A Real World Use Case
Safe Software
 
CIFDAQ'S Market Insight: BTC to ETH money in motion
CIFDAQ
 
Chapter 2 Digital Image Fundamentals.pdf
Getnet Tigabie Askale -(GM)
 
BLW VOCATIONAL TRAINING SUMMER INTERNSHIP REPORT
codernjn73
 
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
madgavkar20181017ppt McKinsey Presentation.pdf
georgschmitzdoerner
 
agentic-ai-and-the-future-of-autonomous-systems.pdf
siddharthnetsavvies
 
Make GenAI investments go further with the Dell AI Factory - Infographic
Principled Technologies
 
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
sujalchauhan1305
 
C Programming Basics concept krnppt.pptx
Karan Prajapat
 
The Evolution of KM Roles (Presented at Knowledge Summit Dublin 2025)
Enterprise Knowledge
 
NewMind AI Weekly Chronicles - July'25 - Week IV
NewMind AI
 
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Principled Technologies
 

Talk Unix Shell Script

  • 1. UNIX Shell Script 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