SlideShare une entreprise Scribd logo
1  sur  20
Advanced Shell Scripting
                recalls, sed, awk and training




                                                     LUG Roma 3
Alessandro Manfredi                      http://www.lugroma3.org
Shell ?




sh, bash, ksh, csh, zsh, ...
How this works
YOU will propose tasks for training

( So, start thinking about them! )
Recalls
   Should be familiar ...


$PS1 : pipes | and | filters
‘ test ‘ conditions
-a, -o, -n : ***, **, ***
-eq, -ne : ******, *** ******
-gt, -lt, -ge, -le : ******* ****, ***** ****
-nt, -ot : ***** ****, ***** ****
-e, -f, -d : ******, ** ****, ** * *********
-b, -c : ******, *********
-r -w -x : ** ********, ** ********, ** **********
-s : **** ******* **** ****
Control structures
if [ condition ]; then action; else action; fi

for i in {1..n}; do action $i; done

for ((c=0;c<10;c++)); do echo $c; done

while read line; do action $line ; done < infile

case $var in 1|3|5) echo 1 ;; *) echo 0 ;; esac

                  Meanings
     $?,    $$,    $#,     $@,        $1,   $2,   $3
Quoting
Double quotes (weak):
  “ $this is going to be interpreted ”
Single quotes (strong):
  ‘ this is not going to be interpreted ‘
Backquotes ( or backticks ):
  ` /this/is/going/to/be/executed/with/its args `
Variables expansion:
  “ ${ /the/result/may/be/quoted! } ”
Order
Brace Expansion         e.g.> ./run_Script_{1..5}.sh

Tilde Expansion            e.g.> echo ~ ~root ~xyz

Variable Expansion             e.g.> echo $var{1..5}

Arithmetic Expansion       e.g.> $(( $value+3*4/2 ))

Command Substitution   e.g.> echo “Today is `date` "

Word Splitting            e.g.> command arg1 arg2

Pathname Expansion        e.g.> ls -lah | grep *.avi
Redirections
> and >> ( without descriptors STDOUT is assumed )

1 is STDOUT, 2 is STDERR

             e.g.: command 1> stdout.txt 2> stderr.txt

2>&1 means “send STDERR to STDOUT”

1>&2 means “send STDOUT to STDERR”

>& and &> without descriptors redirect both 1 and 2
Vars
var=”whatever”
length=${#var}
substring=${var:from:length}

...
                 I/O
read var, read -p “Prompt : “ var
cat
echo $whatever
...
Functions

$ function greet {

> echo “Hello $1”

>}

$ greet “ Mr.`whoami` ”
and another endless tools list...
   (e)grep [...]     uniq
   tail / head       tee
   tr, tr -d         wc
   cut               bc
   getopt(s)         wget
   sort              nc
                     ...
sed
non-interactive stream editor
Sed in pills
sed ‘3d’ - delete the 3rd line of the stream
sed ‘/^$/d’ - delete blank lines
sed -n ‘/pattern/p/ - print all pattern-matching lines
(by default all lines are also echoed, -n to suppress)
sed ‘s/find/replace/g’ - substitute all matching with a
replacement
sed ‘s/quote/”&”/’ - use & to copy the matched
pattern
echo "ff66" | sed 's/([a-z]*)(.*)/21/' - use 1 2
etc to copy portions of the matched pattern
How to use sed

cat file | sed ‘s/search/replace/g’


sed -e ‘cmd’ -i .ext file ( In place editing. If .ext is

given, original files will be moved to file.ext )


sed ‘cmd’ <old_file >new_file
Exercise

What is this ?



find . -print | sed -e 's;[^/]*/;|____;g;s;____|; |;g'



( hint: ; may be used as separators, like / or _ )
AWK
AWK
cat file | awk [opt] ‘pattern {action} [pattern {action}]’

input is parsed in records

foreach record

  foreach pattern

     if record match pattern -> action

default action : print $0

$0 is the entire record

$1 is the 1st field, $2 the 2nd, etc.
AWK
Patterns: BEGIN, END, /regex/, /regex/ in ( &&, ||, ! )

  “” , $3==”value” , $4!=”value” , VAR==”value”

Actions: {var=0}, {print “Field2=”$2}, {print 3*2},

  {var+=1}, {action1 ; action2}

  { for(i=1; i<=NF; i++){printf "-%s- ", $i } print "X" }

  sub(/regex/,”replace”) , gsub(/regex/,”replace”,var)

Options: -v VAR=”value”, -F “FS”

Default variables: FS, RS, NR, NF
Training
... your turn !

Contenu connexe

Tendances

Operating systems system structures
Operating systems   system structuresOperating systems   system structures
Operating systems system structuresMukesh Chinta
 
Chapter 8 Operating Systems And Utility Programs
Chapter 8 Operating Systems And Utility ProgramsChapter 8 Operating Systems And Utility Programs
Chapter 8 Operating Systems And Utility Programsnorzaini
 
Embedded Recipes 2017 - Introduction to Yocto Project/OpenEmbedded - Mylène J...
Embedded Recipes 2017 - Introduction to Yocto Project/OpenEmbedded - Mylène J...Embedded Recipes 2017 - Introduction to Yocto Project/OpenEmbedded - Mylène J...
Embedded Recipes 2017 - Introduction to Yocto Project/OpenEmbedded - Mylène J...Anne Nicolas
 
Principles of operating system
Principles of operating systemPrinciples of operating system
Principles of operating systemAnil Dharmapuri
 
Lesson 2 Understanding Linux File System
Lesson 2 Understanding Linux File SystemLesson 2 Understanding Linux File System
Lesson 2 Understanding Linux File SystemSadia Bashir
 
UNIX Operating System
UNIX Operating SystemUNIX Operating System
UNIX Operating SystemUnless Yuriko
 
File system security
File system securityFile system security
File system securityAmmAr mobark
 
Introduction to Linux
Introduction to Linux Introduction to Linux
Introduction to Linux Harish R
 
Linux process management
Linux process managementLinux process management
Linux process managementRaghu nath
 
Operating System Structure (documentation)
Operating System Structure (documentation)Operating System Structure (documentation)
Operating System Structure (documentation)Navid Daneshvaran
 
OPERATING SYSTEM SERVICES, OPERATING SYSTEM STRUCTURES
OPERATING SYSTEM SERVICES, OPERATING SYSTEM STRUCTURESOPERATING SYSTEM SERVICES, OPERATING SYSTEM STRUCTURES
OPERATING SYSTEM SERVICES, OPERATING SYSTEM STRUCTURESpriyasoundar
 

Tendances (20)

File system implementation
File system implementationFile system implementation
File system implementation
 
Linux file system
Linux file systemLinux file system
Linux file system
 
linux vs window
linux vs windowlinux vs window
linux vs window
 
Operating systems system structures
Operating systems   system structuresOperating systems   system structures
Operating systems system structures
 
Chapter 8 Operating Systems And Utility Programs
Chapter 8 Operating Systems And Utility ProgramsChapter 8 Operating Systems And Utility Programs
Chapter 8 Operating Systems And Utility Programs
 
Processes and threads
Processes and threadsProcesses and threads
Processes and threads
 
Embedded Recipes 2017 - Introduction to Yocto Project/OpenEmbedded - Mylène J...
Embedded Recipes 2017 - Introduction to Yocto Project/OpenEmbedded - Mylène J...Embedded Recipes 2017 - Introduction to Yocto Project/OpenEmbedded - Mylène J...
Embedded Recipes 2017 - Introduction to Yocto Project/OpenEmbedded - Mylène J...
 
Principles of operating system
Principles of operating systemPrinciples of operating system
Principles of operating system
 
U boot-boot-flow
U boot-boot-flowU boot-boot-flow
U boot-boot-flow
 
Linux Booting Process
Linux Booting ProcessLinux Booting Process
Linux Booting Process
 
Lesson 2 Understanding Linux File System
Lesson 2 Understanding Linux File SystemLesson 2 Understanding Linux File System
Lesson 2 Understanding Linux File System
 
UNIX Operating System
UNIX Operating SystemUNIX Operating System
UNIX Operating System
 
Operating System
Operating SystemOperating System
Operating System
 
Memory management in linux
Memory management in linuxMemory management in linux
Memory management in linux
 
File system security
File system securityFile system security
File system security
 
Introduction to Linux
Introduction to Linux Introduction to Linux
Introduction to Linux
 
Linux process management
Linux process managementLinux process management
Linux process management
 
Operating System Structure (documentation)
Operating System Structure (documentation)Operating System Structure (documentation)
Operating System Structure (documentation)
 
OPERATING SYSTEM SERVICES, OPERATING SYSTEM STRUCTURES
OPERATING SYSTEM SERVICES, OPERATING SYSTEM STRUCTURESOPERATING SYSTEM SERVICES, OPERATING SYSTEM STRUCTURES
OPERATING SYSTEM SERVICES, OPERATING SYSTEM STRUCTURES
 
Case study windows
Case study windowsCase study windows
Case study windows
 

En vedette

En vedette (20)

Testingtechniques And Strategy
Testingtechniques And StrategyTestingtechniques And Strategy
Testingtechniques And Strategy
 
Awk Unix Utility Explained
Awk Unix Utility ExplainedAwk Unix Utility Explained
Awk Unix Utility Explained
 
Unix day3 v1.3
Unix day3 v1.3Unix day3 v1.3
Unix day3 v1.3
 
Unix
UnixUnix
Unix
 
What Linux is what you should also have on your computer.
What Linux is what you should also have on your computer.What Linux is what you should also have on your computer.
What Linux is what you should also have on your computer.
 
Unix day4 v1.3
Unix day4 v1.3Unix day4 v1.3
Unix day4 v1.3
 
Unix day2 v1.3
Unix day2 v1.3Unix day2 v1.3
Unix day2 v1.3
 
Linux 101 Exploring Linux OS
Linux 101 Exploring Linux OSLinux 101 Exploring Linux OS
Linux 101 Exploring Linux OS
 
Presentation of awk
Presentation of awkPresentation of awk
Presentation of awk
 
Awk essentials
Awk essentialsAwk essentials
Awk essentials
 
unix crontab basics
unix crontab basicsunix crontab basics
unix crontab basics
 
UNIX - Class6 - sed - Detail
UNIX - Class6 - sed - DetailUNIX - Class6 - sed - Detail
UNIX - Class6 - sed - Detail
 
Sed Unix Utility Explained
Sed Unix Utility ExplainedSed Unix Utility Explained
Sed Unix Utility Explained
 
Shell script-sec
Shell script-secShell script-sec
Shell script-sec
 
Chap06
Chap06Chap06
Chap06
 
Linux fundamental - Chap 15 Job Scheduling
Linux fundamental - Chap 15 Job SchedulingLinux fundamental - Chap 15 Job Scheduling
Linux fundamental - Chap 15 Job Scheduling
 
Regular Expressions grep and egrep
Regular Expressions grep and egrepRegular Expressions grep and egrep
Regular Expressions grep and egrep
 
Oracle 12c Multi Process Multi Threaded
Oracle 12c Multi Process Multi ThreadedOracle 12c Multi Process Multi Threaded
Oracle 12c Multi Process Multi Threaded
 
Czzawk
CzzawkCzzawk
Czzawk
 
Awk programming
Awk programming Awk programming
Awk programming
 

Similaire à Advanced Shell Scripting

DevChatt 2010 - *nix Cmd Line Kung Foo
DevChatt 2010 - *nix Cmd Line Kung FooDevChatt 2010 - *nix Cmd Line Kung Foo
DevChatt 2010 - *nix Cmd Line Kung Foobrian_dailey
 
Achieving Parsing Sanity In Erlang
Achieving Parsing Sanity In ErlangAchieving Parsing Sanity In Erlang
Achieving Parsing Sanity In ErlangSean Cribbs
 
ShellAdvanced aaäaaaaaaaaaaaaaaaaaaaaaaaaaaa
ShellAdvanced aaäaaaaaaaaaaaaaaaaaaaaaaaaaaaShellAdvanced aaäaaaaaaaaaaaaaaaaaaaaaaaaaaa
ShellAdvanced aaäaaaaaaaaaaaaaaaaaaaaaaaaaaaewout2
 
PERL for QA - Important Commands and applications
PERL for QA - Important Commands and applicationsPERL for QA - Important Commands and applications
PERL for QA - Important Commands and applicationsSunil Kumar Gunasekaran
 
Round PEG, Round Hole - Parsing Functionally
Round PEG, Round Hole - Parsing FunctionallyRound PEG, Round Hole - Parsing Functionally
Round PEG, Round Hole - Parsing FunctionallySean Cribbs
 
Talk Unix Shell Script
Talk Unix Shell ScriptTalk Unix Shell Script
Talk Unix Shell ScriptDr.Ravi
 
Hacking Parse.y with ujihisa
Hacking Parse.y with ujihisaHacking Parse.y with ujihisa
Hacking Parse.y with ujihisaujihisa
 
Shell Scripts
Shell ScriptsShell Scripts
Shell ScriptsDr.Ravi
 
Python language data types
Python language data typesPython language data types
Python language data typesHarry Potter
 
Python language data types
Python language data typesPython language data types
Python language data typesHoang Nguyen
 
Python language data types
Python language data typesPython language data types
Python language data typesLuis Goldster
 
Python language data types
Python language data typesPython language data types
Python language data typesTony Nguyen
 
Python language data types
Python language data typesPython language data types
Python language data typesFraboni Ec
 
Python language data types
Python language data typesPython language data types
Python language data typesJames Wong
 

Similaire à Advanced Shell Scripting (20)

Shell Scripting
Shell ScriptingShell Scripting
Shell Scripting
 
n
nn
n
 
DevChatt 2010 - *nix Cmd Line Kung Foo
DevChatt 2010 - *nix Cmd Line Kung FooDevChatt 2010 - *nix Cmd Line Kung Foo
DevChatt 2010 - *nix Cmd Line Kung Foo
 
Achieving Parsing Sanity In Erlang
Achieving Parsing Sanity In ErlangAchieving Parsing Sanity In Erlang
Achieving Parsing Sanity In Erlang
 
ShellAdvanced aaäaaaaaaaaaaaaaaaaaaaaaaaaaaa
ShellAdvanced aaäaaaaaaaaaaaaaaaaaaaaaaaaaaaShellAdvanced aaäaaaaaaaaaaaaaaaaaaaaaaaaaaa
ShellAdvanced aaäaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
Unix 5 en
Unix 5 enUnix 5 en
Unix 5 en
 
Shell scripting
Shell scriptingShell scripting
Shell scripting
 
PERL for QA - Important Commands and applications
PERL for QA - Important Commands and applicationsPERL for QA - Important Commands and applications
PERL for QA - Important Commands and applications
 
Round PEG, Round Hole - Parsing Functionally
Round PEG, Round Hole - Parsing FunctionallyRound PEG, Round Hole - Parsing Functionally
Round PEG, Round Hole - Parsing Functionally
 
Talk Unix Shell Script
Talk Unix Shell ScriptTalk Unix Shell Script
Talk Unix Shell Script
 
Hacking Parse.y with ujihisa
Hacking Parse.y with ujihisaHacking Parse.y with ujihisa
Hacking Parse.y with ujihisa
 
Bioinformatica p4-io
Bioinformatica p4-ioBioinformatica p4-io
Bioinformatica p4-io
 
Shell programming
Shell programmingShell programming
Shell programming
 
Shell Scripts
Shell ScriptsShell Scripts
Shell Scripts
 
Python language data types
Python language data typesPython language data types
Python language data types
 
Python language data types
Python language data typesPython language data types
Python language data types
 
Python language data types
Python language data typesPython language data types
Python language data types
 
Python language data types
Python language data typesPython language data types
Python language data types
 
Python language data types
Python language data typesPython language data types
Python language data types
 
Python language data types
Python language data typesPython language data types
Python language data types
 

Plus de Alessandro Manfredi

Plus de Alessandro Manfredi (9)

Hey Cloud, it’s the user calling, he says he wants the security back
Hey Cloud, it’s the user calling, he says he wants the security backHey Cloud, it’s the user calling, he says he wants the security back
Hey Cloud, it’s the user calling, he says he wants the security back
 
WhyMCA HappyHour - EUHackathon Part II
WhyMCA HappyHour - EUHackathon Part IIWhyMCA HappyHour - EUHackathon Part II
WhyMCA HappyHour - EUHackathon Part II
 
Connect (4|n)
Connect (4|n)Connect (4|n)
Connect (4|n)
 
LUG - Ricompilazione kernel
LUG - Ricompilazione kernelLUG - Ricompilazione kernel
LUG - Ricompilazione kernel
 
LUG - Logical volumes management
LUG - Logical volumes managementLUG - Logical volumes management
LUG - Logical volumes management
 
LUG - Install Fest 2008
LUG - Install Fest 2008LUG - Install Fest 2008
LUG - Install Fest 2008
 
Find me a roof!
Find me a roof!Find me a roof!
Find me a roof!
 
ExAlg Overview
ExAlg OverviewExAlg Overview
ExAlg Overview
 
The "vi" Text Editor
The "vi" Text EditorThe "vi" Text Editor
The "vi" Text Editor
 

Dernier

IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 

Dernier (20)

IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 

Advanced Shell Scripting

  • 1. Advanced Shell Scripting recalls, sed, awk and training LUG Roma 3 Alessandro Manfredi http://www.lugroma3.org
  • 2. Shell ? sh, bash, ksh, csh, zsh, ...
  • 3. How this works YOU will propose tasks for training ( So, start thinking about them! )
  • 4. Recalls Should be familiar ... $PS1 : pipes | and | filters
  • 5. ‘ test ‘ conditions -a, -o, -n : ***, **, *** -eq, -ne : ******, *** ****** -gt, -lt, -ge, -le : ******* ****, ***** **** -nt, -ot : ***** ****, ***** **** -e, -f, -d : ******, ** ****, ** * ********* -b, -c : ******, ********* -r -w -x : ** ********, ** ********, ** ********** -s : **** ******* **** ****
  • 6. Control structures if [ condition ]; then action; else action; fi for i in {1..n}; do action $i; done for ((c=0;c<10;c++)); do echo $c; done while read line; do action $line ; done < infile case $var in 1|3|5) echo 1 ;; *) echo 0 ;; esac Meanings $?, $$, $#, $@, $1, $2, $3
  • 7. Quoting Double quotes (weak): “ $this is going to be interpreted ” Single quotes (strong): ‘ this is not going to be interpreted ‘ Backquotes ( or backticks ): ` /this/is/going/to/be/executed/with/its args ` Variables expansion: “ ${ /the/result/may/be/quoted! } ”
  • 8. Order Brace Expansion e.g.> ./run_Script_{1..5}.sh Tilde Expansion e.g.> echo ~ ~root ~xyz Variable Expansion e.g.> echo $var{1..5} Arithmetic Expansion e.g.> $(( $value+3*4/2 )) Command Substitution e.g.> echo “Today is `date` " Word Splitting e.g.> command arg1 arg2 Pathname Expansion e.g.> ls -lah | grep *.avi
  • 9. Redirections > and >> ( without descriptors STDOUT is assumed ) 1 is STDOUT, 2 is STDERR e.g.: command 1> stdout.txt 2> stderr.txt 2>&1 means “send STDERR to STDOUT” 1>&2 means “send STDOUT to STDERR” >& and &> without descriptors redirect both 1 and 2
  • 10. Vars var=”whatever” length=${#var} substring=${var:from:length} ... I/O read var, read -p “Prompt : “ var cat echo $whatever ...
  • 11. Functions $ function greet { > echo “Hello $1” >} $ greet “ Mr.`whoami` ”
  • 12. and another endless tools list... (e)grep [...] uniq tail / head tee tr, tr -d wc cut bc getopt(s) wget sort nc ...
  • 14. Sed in pills sed ‘3d’ - delete the 3rd line of the stream sed ‘/^$/d’ - delete blank lines sed -n ‘/pattern/p/ - print all pattern-matching lines (by default all lines are also echoed, -n to suppress) sed ‘s/find/replace/g’ - substitute all matching with a replacement sed ‘s/quote/”&”/’ - use & to copy the matched pattern echo "ff66" | sed 's/([a-z]*)(.*)/21/' - use 1 2 etc to copy portions of the matched pattern
  • 15. How to use sed cat file | sed ‘s/search/replace/g’ sed -e ‘cmd’ -i .ext file ( In place editing. If .ext is given, original files will be moved to file.ext ) sed ‘cmd’ <old_file >new_file
  • 16. Exercise What is this ? find . -print | sed -e 's;[^/]*/;|____;g;s;____|; |;g' ( hint: ; may be used as separators, like / or _ )
  • 17. AWK
  • 18. AWK cat file | awk [opt] ‘pattern {action} [pattern {action}]’ input is parsed in records foreach record foreach pattern if record match pattern -> action default action : print $0 $0 is the entire record $1 is the 1st field, $2 the 2nd, etc.
  • 19. AWK Patterns: BEGIN, END, /regex/, /regex/ in ( &&, ||, ! ) “” , $3==”value” , $4!=”value” , VAR==”value” Actions: {var=0}, {print “Field2=”$2}, {print 3*2}, {var+=1}, {action1 ; action2} { for(i=1; i<=NF; i++){printf "-%s- ", $i } print "X" } sub(/regex/,”replace”) , gsub(/regex/,”replace”,var) Options: -v VAR=”value”, -F “FS” Default variables: FS, RS, NR, NF

Notes de l'éditeur