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

What's hot (20)

Bash Shell Scripting
Bash Shell ScriptingBash Shell Scripting
Bash Shell Scripting
Raghu nath
 
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
 
Shell scripting
Shell scriptingShell scripting
Shell scripting
Manav Prasad
 
Shell Scripting
Shell ScriptingShell Scripting
Shell Scripting
Gaurav Shinde
 
Chap06
Chap06Chap06
Chap06
Dr.Ravi
 
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
 
Quick start bash script
Quick start   bash scriptQuick start   bash script
Quick start bash script
Simon Su
 
Unix shell scripting
Unix shell scriptingUnix shell scripting
Unix shell scripting
Pavan Devarakonda
 
Shell Scripts
Shell ScriptsShell Scripts
Shell Scripts
Dr.Ravi
 
Bash shell
Bash shellBash shell
Bash shell
xylas121
 
Shell scripting
Shell scriptingShell scripting
Shell scripting
Ashrith Mekala
 
Unix - Shell Scripts
Unix - Shell ScriptsUnix - Shell Scripts
Unix - Shell Scripts
ananthimurugesan
 
Bash Shell Scripting
Bash Shell ScriptingBash Shell Scripting
Bash Shell Scripting
Raghu nath
 
Shell scripting
Shell scriptingShell scripting
Shell scripting
Geeks Anonymes
 
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
 
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
 
Unix lab manual
Unix lab manualUnix lab manual
Unix lab manual
Chaitanya Kn
 
Easiest way to start with Shell scripting
Easiest way to start with Shell scriptingEasiest way to start with Shell scripting
Easiest way to start with Shell scripting
Akshay Siwal
 
Bash Shell Scripting
Bash Shell ScriptingBash Shell Scripting
Bash Shell Scripting
Raghu nath
 
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
 
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
 
Quick start bash script
Quick start   bash scriptQuick start   bash script
Quick start bash script
Simon Su
 
Shell Scripts
Shell ScriptsShell Scripts
Shell Scripts
Dr.Ravi
 
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
 
Easiest way to start with Shell scripting
Easiest way to start with Shell scriptingEasiest way to start with Shell scripting
Easiest way to start with Shell scripting
Akshay Siwal
 

Viewers also liked (8)

Shellprogramming
ShellprogrammingShellprogramming
Shellprogramming
Andrew Vandever
 
Bash Beginners Guide
Bash Beginners GuideBash Beginners Guide
Bash Beginners Guide
Dinesh Vasudevan
 
Purpose of command interpreter
Purpose of command interpreterPurpose of command interpreter
Purpose of command interpreter
Sumant Diwakar
 
operating system structure
operating system structureoperating system structure
operating system structure
Waseem Ud Din Farooqui
 
SysProg-Tutor 02 Introduction to Unix Operating System
SysProg-Tutor 02 Introduction to Unix Operating SystemSysProg-Tutor 02 Introduction to Unix Operating System
SysProg-Tutor 02 Introduction to Unix Operating System
Wongyos Keardsri
 
UNIX Operating System
UNIX Operating SystemUNIX Operating System
UNIX Operating System
Unless Yuriko
 
Unix Operating System
Unix Operating SystemUnix Operating System
Unix Operating System
subhsikha
 
Unix operating system
Unix operating systemUnix operating system
Unix operating system
ABhay Panchal
 
Purpose of command interpreter
Purpose of command interpreterPurpose of command interpreter
Purpose of command interpreter
Sumant Diwakar
 
SysProg-Tutor 02 Introduction to Unix Operating System
SysProg-Tutor 02 Introduction to Unix Operating SystemSysProg-Tutor 02 Introduction to Unix Operating System
SysProg-Tutor 02 Introduction to Unix Operating System
Wongyos Keardsri
 
UNIX Operating System
UNIX Operating SystemUNIX Operating System
UNIX Operating System
Unless Yuriko
 
Unix Operating System
Unix Operating SystemUnix Operating System
Unix Operating System
subhsikha
 
Unix operating system
Unix operating systemUnix operating system
Unix operating system
ABhay Panchal
 
Ad

Similar to Talk Unix Shell Script (20)

First steps in C-Shell
First steps in C-ShellFirst steps in C-Shell
First steps in C-Shell
Brahma Killampalli
 
ShellAdvanced aaäaaaaaaaaaaaaaaaaaaaaaaaaaaa
ShellAdvanced aaäaaaaaaaaaaaaaaaaaaaaaaaaaaaShellAdvanced aaäaaaaaaaaaaaaaaaaaaaaaaaaaaa
ShellAdvanced aaäaaaaaaaaaaaaaaaaaaaaaaaaaaa
ewout2
 
ShellAdvanced shell scripting programm.ppt
ShellAdvanced shell scripting programm.pptShellAdvanced shell scripting programm.ppt
ShellAdvanced shell scripting programm.ppt
ubaidullah75790
 
Perl Presentation
Perl PresentationPerl Presentation
Perl Presentation
Sopan Shewale
 
shellScriptAlt.pptx
shellScriptAlt.pptxshellScriptAlt.pptx
shellScriptAlt.pptx
NiladriDey18
 
Unix
UnixUnix
Unix
nazeer pasha
 
Shell programming
Shell programmingShell programming
Shell programming
Moayad Moawiah
 
You Can Do It! Start Using Perl to Handle Your Voyager Needs
You Can Do It! Start Using Perl to Handle Your Voyager NeedsYou Can Do It! Start Using Perl to Handle Your Voyager Needs
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...
Bioinformatica: Esercizi su Perl, espressioni regolari e altre amenità (BMR G...Bioinformatica: Esercizi su Perl, espressioni regolari e altre amenità (BMR G...
Bioinformatica: Esercizi su Perl, espressioni regolari e altre amenità (BMR G...
Andrea Telatin
 
Module 03 Programming on Linux
Module 03 Programming on LinuxModule 03 Programming on Linux
Module 03 Programming on Linux
Tushar B Kute
 
Lecture 3 Perl & FreeBSD administration
Lecture 3 Perl & FreeBSD administrationLecture 3 Perl & FreeBSD administration
Lecture 3 Perl & FreeBSD administration
Mohammed Farrag
 
KT on Bash Script.pptx
KT on Bash Script.pptxKT on Bash Script.pptx
KT on Bash Script.pptx
gogulasivannarayana
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to Perl
Dave Cross
 
Bioinformatica 29-09-2011-p1-introduction
Bioinformatica 29-09-2011-p1-introductionBioinformatica 29-09-2011-p1-introduction
Bioinformatica 29-09-2011-p1-introduction
Prof. Wim Van Criekinge
 
Introduction to Perl - Day 1
Introduction to Perl - Day 1Introduction to Perl - Day 1
Introduction to Perl - Day 1
Dave Cross
 
Unix Tutorial
Unix TutorialUnix Tutorial
Unix Tutorial
Sanjay Saluth
 
Perl courseparti
Perl coursepartiPerl courseparti
Perl courseparti
ernlow
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to Perl
NBACriteria2SICET
 
390aLecture05_12sp.ppt
390aLecture05_12sp.ppt390aLecture05_12sp.ppt
390aLecture05_12sp.ppt
mugeshmsd5
 
Linux Shell Scripting
Linux Shell ScriptingLinux Shell Scripting
Linux Shell Scripting
Raghu nath
 
ShellAdvanced aaäaaaaaaaaaaaaaaaaaaaaaaaaaaa
ShellAdvanced aaäaaaaaaaaaaaaaaaaaaaaaaaaaaaShellAdvanced aaäaaaaaaaaaaaaaaaaaaaaaaaaaaa
ShellAdvanced aaäaaaaaaaaaaaaaaaaaaaaaaaaaaa
ewout2
 
ShellAdvanced shell scripting programm.ppt
ShellAdvanced shell scripting programm.pptShellAdvanced shell scripting programm.ppt
ShellAdvanced shell scripting programm.ppt
ubaidullah75790
 
shellScriptAlt.pptx
shellScriptAlt.pptxshellScriptAlt.pptx
shellScriptAlt.pptx
NiladriDey18
 
You Can Do It! Start Using Perl to Handle Your Voyager Needs
You Can Do It! Start Using Perl to Handle Your Voyager NeedsYou Can Do It! Start Using Perl to Handle Your Voyager Needs
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...
Bioinformatica: Esercizi su Perl, espressioni regolari e altre amenità (BMR G...Bioinformatica: Esercizi su Perl, espressioni regolari e altre amenità (BMR G...
Bioinformatica: Esercizi su Perl, espressioni regolari e altre amenità (BMR G...
Andrea Telatin
 
Module 03 Programming on Linux
Module 03 Programming on LinuxModule 03 Programming on Linux
Module 03 Programming on Linux
Tushar B Kute
 
Lecture 3 Perl & FreeBSD administration
Lecture 3 Perl & FreeBSD administrationLecture 3 Perl & FreeBSD administration
Lecture 3 Perl & FreeBSD administration
Mohammed Farrag
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to Perl
Dave Cross
 
Bioinformatica 29-09-2011-p1-introduction
Bioinformatica 29-09-2011-p1-introductionBioinformatica 29-09-2011-p1-introduction
Bioinformatica 29-09-2011-p1-introduction
Prof. Wim Van Criekinge
 
Introduction to Perl - Day 1
Introduction to Perl - Day 1Introduction to Perl - Day 1
Introduction to Perl - Day 1
Dave Cross
 
Perl courseparti
Perl coursepartiPerl courseparti
Perl courseparti
ernlow
 
390aLecture05_12sp.ppt
390aLecture05_12sp.ppt390aLecture05_12sp.ppt
390aLecture05_12sp.ppt
mugeshmsd5
 
Linux Shell Scripting
Linux Shell ScriptingLinux Shell Scripting
Linux Shell Scripting
Raghu nath
 
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
 

Recently uploaded (20)

Crypto Super 500 - 14th Report - June2025.pdf
Crypto Super 500 - 14th Report - June2025.pdfCrypto Super 500 - 14th Report - June2025.pdf
Crypto Super 500 - 14th Report - June2025.pdf
Stephen Perrenod
 
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
 
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
NTT DATA Technology & Innovation
 
Data Validation and System Interoperability
Data Validation and System InteroperabilityData Validation and System Interoperability
Data Validation and System Interoperability
Safe Software
 
Providing an OGC API Processes REST Interface for FME Flow
Providing an OGC API Processes REST Interface for FME FlowProviding an OGC API Processes REST Interface for FME Flow
Providing an OGC API Processes REST Interface for FME Flow
Safe Software
 
War_And_Cyber_3_Years_Of_Struggle_And_Lessons_For_Global_Security.pdf
War_And_Cyber_3_Years_Of_Struggle_And_Lessons_For_Global_Security.pdfWar_And_Cyber_3_Years_Of_Struggle_And_Lessons_For_Global_Security.pdf
War_And_Cyber_3_Years_Of_Struggle_And_Lessons_For_Global_Security.pdf
biswajitbanerjee38
 
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
 
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
 
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
 
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
 
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
Safe Software
 
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven InfrastructureNo-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
Safe Software
 
FME for Distribution & Transmission Integrity Management Program (DIMP & TIMP)
FME for Distribution & Transmission Integrity Management Program (DIMP & TIMP)FME for Distribution & Transmission Integrity Management Program (DIMP & TIMP)
FME for Distribution & Transmission Integrity Management Program (DIMP & TIMP)
Safe Software
 
Murdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementaryMurdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementary
JorgeSemperteguiMont
 
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
 
“Addressing Evolving AI Model Challenges Through Memory and Storage,” a Prese...
“Addressing Evolving AI Model Challenges Through Memory and Storage,” a Prese...“Addressing Evolving AI Model Challenges Through Memory and Storage,” a Prese...
“Addressing Evolving AI Model Challenges Through Memory and Storage,” a Prese...
Edge AI and Vision Alliance
 
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Safe Software
 
FIDO Seminar: Evolving Landscape of Post-Quantum Cryptography.pptx
FIDO Seminar: Evolving Landscape of Post-Quantum Cryptography.pptxFIDO Seminar: Evolving Landscape of Post-Quantum Cryptography.pptx
FIDO Seminar: Evolving Landscape of Post-Quantum Cryptography.pptx
FIDO Alliance
 
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
 
AudGram Review: Build Visually Appealing, AI-Enhanced Audiograms to Engage Yo...
AudGram Review: Build Visually Appealing, AI-Enhanced Audiograms to Engage Yo...AudGram Review: Build Visually Appealing, AI-Enhanced Audiograms to Engage Yo...
AudGram Review: Build Visually Appealing, AI-Enhanced Audiograms to Engage Yo...
SOFTTECHHUB
 
Crypto Super 500 - 14th Report - June2025.pdf
Crypto Super 500 - 14th Report - June2025.pdfCrypto Super 500 - 14th Report - June2025.pdf
Crypto Super 500 - 14th Report - June2025.pdf
Stephen Perrenod
 
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
 
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
NTT DATA Technology & Innovation
 
Data Validation and System Interoperability
Data Validation and System InteroperabilityData Validation and System Interoperability
Data Validation and System Interoperability
Safe Software
 
Providing an OGC API Processes REST Interface for FME Flow
Providing an OGC API Processes REST Interface for FME FlowProviding an OGC API Processes REST Interface for FME Flow
Providing an OGC API Processes REST Interface for FME Flow
Safe Software
 
War_And_Cyber_3_Years_Of_Struggle_And_Lessons_For_Global_Security.pdf
War_And_Cyber_3_Years_Of_Struggle_And_Lessons_For_Global_Security.pdfWar_And_Cyber_3_Years_Of_Struggle_And_Lessons_For_Global_Security.pdf
War_And_Cyber_3_Years_Of_Struggle_And_Lessons_For_Global_Security.pdf
biswajitbanerjee38
 
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
 
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
 
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
 
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
 
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
Safe Software
 
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven InfrastructureNo-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
Safe Software
 
FME for Distribution & Transmission Integrity Management Program (DIMP & TIMP)
FME for Distribution & Transmission Integrity Management Program (DIMP & TIMP)FME for Distribution & Transmission Integrity Management Program (DIMP & TIMP)
FME for Distribution & Transmission Integrity Management Program (DIMP & TIMP)
Safe Software
 
Murdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementaryMurdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementary
JorgeSemperteguiMont
 
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
 
“Addressing Evolving AI Model Challenges Through Memory and Storage,” a Prese...
“Addressing Evolving AI Model Challenges Through Memory and Storage,” a Prese...“Addressing Evolving AI Model Challenges Through Memory and Storage,” a Prese...
“Addressing Evolving AI Model Challenges Through Memory and Storage,” a Prese...
Edge AI and Vision Alliance
 
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Safe Software
 
FIDO Seminar: Evolving Landscape of Post-Quantum Cryptography.pptx
FIDO Seminar: Evolving Landscape of Post-Quantum Cryptography.pptxFIDO Seminar: Evolving Landscape of Post-Quantum Cryptography.pptx
FIDO Seminar: Evolving Landscape of Post-Quantum Cryptography.pptx
FIDO Alliance
 
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
 
AudGram Review: Build Visually Appealing, AI-Enhanced Audiograms to Engage Yo...
AudGram Review: Build Visually Appealing, AI-Enhanced Audiograms to Engage Yo...AudGram Review: Build Visually Appealing, AI-Enhanced Audiograms to Engage Yo...
AudGram Review: Build Visually Appealing, AI-Enhanced Audiograms to Engage Yo...
SOFTTECHHUB
 

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