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

What's hot (20)

Introduction to Bash Scripting, Zyxware Technologies, CSI Students Convention...
Introduction to Bash Scripting, Zyxware Technologies, CSI Students Convention...Introduction to Bash Scripting, Zyxware Technologies, CSI Students Convention...
Introduction to Bash Scripting, Zyxware Technologies, CSI Students Convention...
Zyxware Technologies
 
Shell scripting
Shell scriptingShell scripting
Shell scripting
Manav Prasad
 
Introduction to shell scripting
Introduction to shell scriptingIntroduction to shell scripting
Introduction to shell scripting
Corrado Santoro
 
Chap06
Chap06Chap06
Chap06
Dr.Ravi
 
Unix Shell Scripting Basics
Unix Shell Scripting BasicsUnix Shell Scripting Basics
Unix Shell Scripting Basics
Sudharsan S
 
Shell Scripting
Shell ScriptingShell Scripting
Shell Scripting
Gaurav Shinde
 
Quick start bash script
Quick start   bash scriptQuick start   bash script
Quick start bash script
Simon Su
 
Unix Shell Scripting Basics
Unix Shell Scripting BasicsUnix Shell Scripting Basics
Unix Shell Scripting Basics
Dr.Ravi
 
Unix And Shell Scripting
Unix And Shell ScriptingUnix And Shell Scripting
Unix And Shell Scripting
Jaibeer Malik
 
Shell Scripts
Shell ScriptsShell Scripts
Shell Scripts
Dr.Ravi
 
Unix lab manual
Unix lab manualUnix lab manual
Unix lab manual
Chaitanya Kn
 
Unix - Shell Scripts
Unix - Shell ScriptsUnix - Shell Scripts
Unix - Shell Scripts
ananthimurugesan
 
Unix 1st sem lab programs a - VTU Karnataka
Unix 1st sem lab programs a - VTU KarnatakaUnix 1st sem lab programs a - VTU Karnataka
Unix 1st sem lab programs a - VTU Karnataka
iCreateWorld
 
Bash shell
Bash shellBash shell
Bash shell
xylas121
 
Bash Shell Scripting
Bash Shell ScriptingBash Shell Scripting
Bash Shell Scripting
Raghu nath
 
Unix shell scripting
Unix shell scriptingUnix shell scripting
Unix shell scripting
Pavan Devarakonda
 
Shell scripting
Shell scriptingShell scripting
Shell scripting
Ashrith Mekala
 
First steps in C-Shell
First steps in C-ShellFirst steps in C-Shell
First steps in C-Shell
Brahma Killampalli
 
Unix shell scripts
Unix shell scriptsUnix shell scripts
Unix shell scripts
Prakash Lambha
 
COSCUP2012: How to write a bash script like the python?
COSCUP2012: How to write a bash script like the python?COSCUP2012: How to write a bash script like the python?
COSCUP2012: How to write a bash script like the python?
Lloyd Huang
 
Introduction to Bash Scripting, Zyxware Technologies, CSI Students Convention...
Introduction to Bash Scripting, Zyxware Technologies, CSI Students Convention...Introduction to Bash Scripting, Zyxware Technologies, CSI Students Convention...
Introduction to Bash Scripting, Zyxware Technologies, CSI Students Convention...
Zyxware Technologies
 
Introduction to shell scripting
Introduction to shell scriptingIntroduction to shell scripting
Introduction to shell scripting
Corrado Santoro
 
Unix Shell Scripting Basics
Unix Shell Scripting BasicsUnix Shell Scripting Basics
Unix Shell Scripting Basics
Sudharsan S
 
Quick start bash script
Quick start   bash scriptQuick start   bash script
Quick start bash script
Simon Su
 
Unix Shell Scripting Basics
Unix Shell Scripting BasicsUnix Shell Scripting Basics
Unix Shell Scripting Basics
Dr.Ravi
 
Unix And Shell Scripting
Unix And Shell ScriptingUnix And Shell Scripting
Unix And Shell Scripting
Jaibeer Malik
 
Shell Scripts
Shell ScriptsShell Scripts
Shell Scripts
Dr.Ravi
 
Unix 1st sem lab programs a - VTU Karnataka
Unix 1st sem lab programs a - VTU KarnatakaUnix 1st sem lab programs a - VTU Karnataka
Unix 1st sem lab programs a - VTU Karnataka
iCreateWorld
 
Bash shell
Bash shellBash shell
Bash shell
xylas121
 
Bash Shell Scripting
Bash Shell ScriptingBash Shell Scripting
Bash Shell Scripting
Raghu nath
 
COSCUP2012: How to write a bash script like the python?
COSCUP2012: How to write a bash script like the python?COSCUP2012: How to write a bash script like the python?
COSCUP2012: How to write a bash script like the python?
Lloyd Huang
 

Similar to Talk Unix Shell Script 1 (20)

Unix
UnixUnix
Unix
nazeer pasha
 
Shell programming
Shell programmingShell programming
Shell programming
Moayad Moawiah
 
One-Liners to Rule Them All
One-Liners to Rule Them AllOne-Liners to Rule Them All
One-Liners to Rule Them All
egypt
 
(Ebook) linux shell scripting tutorial
(Ebook) linux shell scripting tutorial(Ebook) linux shell scripting tutorial
(Ebook) linux shell scripting tutorial
jayaramprabhu
 
21bUc8YeDzZpE
21bUc8YeDzZpE21bUc8YeDzZpE
21bUc8YeDzZpE
Aniruddh Tyagi
 
21bUc8YeDzZpE
21bUc8YeDzZpE21bUc8YeDzZpE
21bUc8YeDzZpE
aniruddh Tyagi
 
21bUc8YeDzZpE
21bUc8YeDzZpE21bUc8YeDzZpE
21bUc8YeDzZpE
aniruddh Tyagi
 
Bash
BashBash
Bash
KLabCyscorpions-TechBlog
 
Slides
SlidesSlides
Slides
abhishekvirmani
 
shellScriptAlt.pptx
shellScriptAlt.pptxshellScriptAlt.pptx
shellScriptAlt.pptx
NiladriDey18
 
COMELEC III - Bash unit 1
COMELEC III - Bash unit 1COMELEC III - Bash unit 1
COMELEC III - Bash unit 1
Binsent Ribera
 
Shell scripting
Shell scriptingShell scripting
Shell scripting
Mufaddal Haidermota
 
Shell Scripting crash course.pdf
Shell Scripting crash course.pdfShell Scripting crash course.pdf
Shell Scripting crash course.pdf
harikrishnapolaki
 
Introduction to UNIX
Introduction to UNIXIntroduction to UNIX
Introduction to UNIX
Bioinformatics and Computational Biosciences Branch
 
Productive bash
Productive bashProductive bash
Productive bash
Ayla Khan
 
Advanced Shell Scripting
Advanced Shell ScriptingAdvanced Shell Scripting
Advanced Shell Scripting
Alessandro Manfredi
 
01c shell
01c shell01c shell
01c shell
Kevin Lee
 
Bash Cheat Sheet - SniferL4bs
Bash Cheat Sheet - SniferL4bsBash Cheat Sheet - SniferL4bs
Bash Cheat Sheet - SniferL4bs
Jose Moruno Cadima
 
Scripting and the shell in LINUX
Scripting and the shell in LINUXScripting and the shell in LINUX
Scripting and the shell in LINUX
Bhushan Pawar -Java Trainer
 
Bash Scripting Workshop
Bash Scripting WorkshopBash Scripting Workshop
Bash Scripting Workshop
Ahmed Magdy Ezzeldin, MSc.
 
Ad

More from Dr.Ravi (18)

Corporate Overview
Corporate  OverviewCorporate  Overview
Corporate Overview
Dr.Ravi
 
Excel For The Ceo
Excel For The CeoExcel For The Ceo
Excel For The Ceo
Dr.Ravi
 
Project Specs Pf
Project Specs PfProject Specs Pf
Project Specs Pf
Dr.Ravi
 
Pf Day5
Pf Day5Pf Day5
Pf Day5
Dr.Ravi
 
Assignments Programming Fundamentals
Assignments Programming FundamentalsAssignments Programming Fundamentals
Assignments Programming Fundamentals
Dr.Ravi
 
Hdd Chssc
Hdd ChsscHdd Chssc
Hdd Chssc
Dr.Ravi
 
Chssc Day3
Chssc Day3Chssc Day3
Chssc Day3
Dr.Ravi
 
Chssc Day1
Chssc Day1Chssc Day1
Chssc Day1
Dr.Ravi
 
Pf Day3
Pf Day3Pf Day3
Pf Day3
Dr.Ravi
 
Ldd Pf
Ldd PfLdd Pf
Ldd Pf
Dr.Ravi
 
Chssc Assignments
Chssc AssignmentsChssc Assignments
Chssc Assignments
Dr.Ravi
 
Chssc Day4
Chssc Day4Chssc Day4
Chssc Day4
Dr.Ravi
 
Chssc Day2
Chssc Day2Chssc Day2
Chssc Day2
Dr.Ravi
 
Unix Lec2
Unix Lec2Unix Lec2
Unix Lec2
Dr.Ravi
 
Unix Book
Unix BookUnix Book
Unix Book
Dr.Ravi
 
Unix Basics 04sp
Unix Basics 04spUnix Basics 04sp
Unix Basics 04sp
Dr.Ravi
 
Wicked Cool Shell Scripts
Wicked Cool Shell ScriptsWicked Cool Shell Scripts
Wicked Cool Shell Scripts
Dr.Ravi
 
SAP INTRO
SAP INTROSAP INTRO
SAP INTRO
Dr.Ravi
 
Corporate Overview
Corporate  OverviewCorporate  Overview
Corporate Overview
Dr.Ravi
 
Excel For The Ceo
Excel For The CeoExcel For The Ceo
Excel For The Ceo
Dr.Ravi
 
Project Specs Pf
Project Specs PfProject Specs Pf
Project Specs Pf
Dr.Ravi
 
Assignments Programming Fundamentals
Assignments Programming FundamentalsAssignments Programming Fundamentals
Assignments Programming Fundamentals
Dr.Ravi
 
Hdd Chssc
Hdd ChsscHdd Chssc
Hdd Chssc
Dr.Ravi
 
Chssc Day3
Chssc Day3Chssc Day3
Chssc Day3
Dr.Ravi
 
Chssc Day1
Chssc Day1Chssc Day1
Chssc Day1
Dr.Ravi
 
Chssc Assignments
Chssc AssignmentsChssc Assignments
Chssc Assignments
Dr.Ravi
 
Chssc Day4
Chssc Day4Chssc Day4
Chssc Day4
Dr.Ravi
 
Chssc Day2
Chssc Day2Chssc Day2
Chssc Day2
Dr.Ravi
 
Unix Lec2
Unix Lec2Unix Lec2
Unix Lec2
Dr.Ravi
 
Unix Book
Unix BookUnix Book
Unix Book
Dr.Ravi
 
Unix Basics 04sp
Unix Basics 04spUnix Basics 04sp
Unix Basics 04sp
Dr.Ravi
 
Wicked Cool Shell Scripts
Wicked Cool Shell ScriptsWicked Cool Shell Scripts
Wicked Cool Shell Scripts
Dr.Ravi
 
SAP INTRO
SAP INTROSAP INTRO
SAP INTRO
Dr.Ravi
 
Ad

Recently uploaded (20)

June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
Ivanti
 
Kubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too LateKubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too Late
Michael Furman
 
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Anish Kumar
 
Murdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementaryMurdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementary
JorgeSemperteguiMont
 
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Shashikant Jagtap
 
Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...
BookNet Canada
 
Supporting the NextGen 911 Digital Transformation with FME
Supporting the NextGen 911 Digital Transformation with FMESupporting the NextGen 911 Digital Transformation with FME
Supporting the NextGen 911 Digital Transformation with FME
Safe Software
 
PyData - Graph Theory for Multi-Agent Integration
PyData - Graph Theory for Multi-Agent IntegrationPyData - Graph Theory for Multi-Agent Integration
PyData - Graph Theory for Multi-Agent Integration
barqawicloud
 
FIDO Seminar: Perspectives on Passkeys & Consumer Adoption.pptx
FIDO Seminar: Perspectives on Passkeys & Consumer Adoption.pptxFIDO Seminar: Perspectives on Passkeys & Consumer Adoption.pptx
FIDO Seminar: Perspectives on Passkeys & Consumer Adoption.pptx
FIDO Alliance
 
Oracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI FoundationsOracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI Foundations
VICTOR MAESTRE RAMIREZ
 
Oracle Cloud and AI Specialization Program
Oracle Cloud and AI Specialization ProgramOracle Cloud and AI Specialization Program
Oracle Cloud and AI Specialization Program
VICTOR MAESTRE RAMIREZ
 
FIDO Alliance Seminar State of Passkeys.pptx
FIDO Alliance Seminar State of Passkeys.pptxFIDO Alliance Seminar State of Passkeys.pptx
FIDO Alliance Seminar State of Passkeys.pptx
FIDO Alliance
 
Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025
Safe Software
 
FIDO Seminar: Targeting Trust: The Future of Identity in the Workforce.pptx
FIDO Seminar: Targeting Trust: The Future of Identity in the Workforce.pptxFIDO Seminar: Targeting Trust: The Future of Identity in the Workforce.pptx
FIDO Seminar: Targeting Trust: The Future of Identity in the Workforce.pptx
FIDO Alliance
 
Introduction to Typescript - GDG On Campus EUE
Introduction to Typescript - GDG On Campus EUEIntroduction to Typescript - GDG On Campus EUE
Introduction to Typescript - GDG On Campus EUE
Google Developer Group On Campus European Universities in Egypt
 
Down the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training RoadblocksDown the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training Roadblocks
Rustici Software
 
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
angelo60207
 
ENERGY CONSUMPTION CALCULATION IN ENERGY-EFFICIENT AIR CONDITIONER.pdf
ENERGY CONSUMPTION CALCULATION IN ENERGY-EFFICIENT AIR CONDITIONER.pdfENERGY CONSUMPTION CALCULATION IN ENERGY-EFFICIENT AIR CONDITIONER.pdf
ENERGY CONSUMPTION CALCULATION IN ENERGY-EFFICIENT AIR CONDITIONER.pdf
Muhammad Rizwan Akram
 
FME for Good: Integrating Multiple Data Sources with APIs to Support Local Ch...
FME for Good: Integrating Multiple Data Sources with APIs to Support Local Ch...FME for Good: Integrating Multiple Data Sources with APIs to Support Local Ch...
FME for Good: Integrating Multiple Data Sources with APIs to Support Local Ch...
Safe Software
 
Your startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean accountYour startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean account
angelo60207
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
Ivanti
 
Kubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too LateKubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too Late
Michael Furman
 
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Anish Kumar
 
Murdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementaryMurdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementary
JorgeSemperteguiMont
 
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Shashikant Jagtap
 
Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...
BookNet Canada
 
Supporting the NextGen 911 Digital Transformation with FME
Supporting the NextGen 911 Digital Transformation with FMESupporting the NextGen 911 Digital Transformation with FME
Supporting the NextGen 911 Digital Transformation with FME
Safe Software
 
PyData - Graph Theory for Multi-Agent Integration
PyData - Graph Theory for Multi-Agent IntegrationPyData - Graph Theory for Multi-Agent Integration
PyData - Graph Theory for Multi-Agent Integration
barqawicloud
 
FIDO Seminar: Perspectives on Passkeys & Consumer Adoption.pptx
FIDO Seminar: Perspectives on Passkeys & Consumer Adoption.pptxFIDO Seminar: Perspectives on Passkeys & Consumer Adoption.pptx
FIDO Seminar: Perspectives on Passkeys & Consumer Adoption.pptx
FIDO Alliance
 
Oracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI FoundationsOracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI Foundations
VICTOR MAESTRE RAMIREZ
 
Oracle Cloud and AI Specialization Program
Oracle Cloud and AI Specialization ProgramOracle Cloud and AI Specialization Program
Oracle Cloud and AI Specialization Program
VICTOR MAESTRE RAMIREZ
 
FIDO Alliance Seminar State of Passkeys.pptx
FIDO Alliance Seminar State of Passkeys.pptxFIDO Alliance Seminar State of Passkeys.pptx
FIDO Alliance Seminar State of Passkeys.pptx
FIDO Alliance
 
Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025
Safe Software
 
FIDO Seminar: Targeting Trust: The Future of Identity in the Workforce.pptx
FIDO Seminar: Targeting Trust: The Future of Identity in the Workforce.pptxFIDO Seminar: Targeting Trust: The Future of Identity in the Workforce.pptx
FIDO Seminar: Targeting Trust: The Future of Identity in the Workforce.pptx
FIDO Alliance
 
Down the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training RoadblocksDown the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training Roadblocks
Rustici Software
 
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
angelo60207
 
ENERGY CONSUMPTION CALCULATION IN ENERGY-EFFICIENT AIR CONDITIONER.pdf
ENERGY CONSUMPTION CALCULATION IN ENERGY-EFFICIENT AIR CONDITIONER.pdfENERGY CONSUMPTION CALCULATION IN ENERGY-EFFICIENT AIR CONDITIONER.pdf
ENERGY CONSUMPTION CALCULATION IN ENERGY-EFFICIENT AIR CONDITIONER.pdf
Muhammad Rizwan Akram
 
FME for Good: Integrating Multiple Data Sources with APIs to Support Local Ch...
FME for Good: Integrating Multiple Data Sources with APIs to Support Local Ch...FME for Good: Integrating Multiple Data Sources with APIs to Support Local Ch...
FME for Good: Integrating Multiple Data Sources with APIs to Support Local Ch...
Safe Software
 
Your startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean accountYour startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean account
angelo60207
 

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