SlideShare a Scribd company logo
UNIX Shell-Scripting Basics
Agenda What is a shell?  A shell script? Introduction to  bash Running Commands Applied Shell Programming
What is a shell? % ▌
What is a shell? /bin/bash
What is a shell? #!/bin/bash
What is a shell? INPUT shell OUTPUT ERROR
What is a shell? Any Program But there are a few popular shells…
Bourne Shells /bin/sh /bin/bash “Bourne-Again Shell” Steve Bourne
Other Common Shells C Shell ( /bin/csh ) Turbo C Shell ( /bin/tcsh ) Korn Shell ( /bin/ksh )
An aside: What do I mean by /bin ? C Shell ( /bin/csh ) Turbo C Shell ( /bin/tcsh ) Korn Shell ( /bin/ksh )
An aside: What do I mean by /bin ? /bin, /usr/bin, /usr/local/bin /sbin, /usr/sbin, /usr/local/sbin /tmp /dev /home/borwicjh
What is a Shell Script? A Text File With Instructions Executable
What is a Shell Script? % cat > hello.sh <<MY_PROGRAM #!/bin/sh echo ‘Hello, world’ MY_PROGRAM % chmod +x hello.sh % ./hello.sh Hello, world
What is a Shell Script?  A Text File % cat > hello.sh <<MY_PROGRAM #!/bin/sh echo ‘Hello, world’ MY_PROGRAM % chmod +x hello.sh % ./hello.sh Hello, world
An aside: Redirection cat > /tmp/myfile cat >> /tmp/myfile cat 2> /tmp/myerr cat < /tmp/myinput cat  <<INPUT Some input INPUT cat > /tmp/x  2>&1 0 1 2 INPUT env OUTPUT ERROR
What is a Shell Script?  How To Run % cat > hello.sh <<MY_PROGRAM #!/bin/sh echo ‘Hello, world’ MY_PROGRAM % chmod +x hello.sh % ./hello.sh Hello, world
What is a Shell Script?  What To Do % cat > hello.sh <<MY_PROGRAM #!/bin/sh echo ‘Hello, world’ MY_PROGRAM % chmod +x hello.sh % ./hello.sh Hello, world
What is a Shell Script?  Executable % cat > hello.sh <<MY_PROGRAM #!/bin/sh echo ‘Hello, world’ MY_PROGRAM % chmod +x hello.sh % ./hello.sh Hello, world
What is a Shell Script?  Running it % cat > hello.sh <<MY_PROGRAM #!/bin/sh echo ‘Hello, world’ MY_PROGRAM % chmod +x hello.sh % ./hello.sh Hello, world
Finding the program: PATH % ./hello.sh echo  vs.  /usr/bin/echo % echo $PATH /bin:/usr/bin:/usr/local/bin: /home/borwicjh/bin % which echo /usr/bin/echo
Variables and the Environment % hello.sh bash: hello.sh: Command not found % PATH=“$PATH:.” % hello.sh Hello, world
An aside: Quoting % echo  ‘ $USER ’ $USER % echo  “ $USER ” borwicjh % echo “ \” ” ” % echo “deacnet \\ sct” deacnet\sct % echo  ‘ \” ’ \”
Variables and the Environment % env […variables passed to sub-programs…] % NEW_VAR=“Yes” % echo $NEW_VAR Yes % env […PATH but not NEW_VAR…] % export NEW_VAR % env […PATH and NEW_VAR…]
Welcome to Shell Scripting! Shebang! The Environment PATH Input, Output, and Error chmod
How to Learn man man bash man cat man man man –k man –k manual Learning the Bash Shell , 2 nd  Ed. “ Bash Reference” Cards http://www.tldp.org/LDP/abs/html/
Introduction to  bash
Continuing Lines: \ % echo This \ Is \ A \ Very \ Long \ Command Line This Is A Very Long Command Line %
Exit Status $? 0 is True % ls /does/not/exist % echo $? 1 % echo $? 0
Exit Status:  exit % cat > test.sh <<_TEST_ exit 3 _TEST_ % chmod +x test.sh % ./test.sh % echo $? 3
Logic: test % test 1 -lt 10 % echo $? 0 % test 1 == 10 % echo $? 1
Logic: test test [ ] [ 1 –lt 10 ]  [[ ]] [[ “this string” =~ “this” ]] (( )) (( 1 < 10 ))
Logic: test [ -f /etc/passwd ] [ ! –f /etc/passwd ] [ -f /etc/passwd –a –f /etc/shadow ] [ -f /etc/passwd –o –f /etc/shadow ]
An aside:  $(( ))  for Math % echo $(( 1 + 2 )) 3 % echo $(( 2 * 3 )) 6 % echo $(( 1 / 3 )) 0
Logic: if if  something then : # “elif” a contraction of “else if”: elif  something-else then : else then : fi
Logic: if if  [ $USER –eq “borwicjh” ] then : # “elif” a contraction of “else if”: elif  ls /etc/oratab then : else then : fi
Logic: if # see if a file exists if  [ -e /etc/passwd ] then echo “/etc/passwd exists” else echo “/etc/passwd not found!” fi
Logic: for for i in 1 2 3 do echo $i done
Logic: for for i in  /* do echo “Listing $i:” ls -l $i read done
Logic: for for i in /* do echo “Listing $i:” ls -l $i read done
Logic: for for i in /* do echo “Listing $i:” ls -l $i read done
Logic: C-style for for (( expr1  ; expr2  ; expr3  )) do list done
Logic: C-style for LIMIT=10 for ((  a=1   ; a<=LIMIT  ; a++  )) do echo –n “$a ” done
Logic: while while  something do : done
Logic: while a=0; LIMIT=10 while [  &quot;$a&quot; -lt &quot;$LIMIT&quot;  ] do echo -n &quot;$a ” a=$(( a + 1 )) done
Counters COUNTER=0 while [ -e “$FILE.COUNTER” ] do COUNTER=$(( COUNTER + 1)) done Note: race condition
Reusing Code: “Sourcing” % cat > /path/to/my/passwords <<_PW_ FTP_USER=“sct” _PW_ % echo $FTP_USER %  .  /path/to/my/passwords % echo $FTP_USER sct %
Variable Manipulation % FILEPATH=/path/to/my/output.lis % echo $FILEPATH /path/to/my/output.lis % echo ${FILEPATH %.lis } /path/to/my/output % echo ${FILEPATH #*/ } path/to/my/output.lis % echo ${FILEPATH ##*/ } output.lis
It takes a long time to become a bash guru…
Running Programs
Reasons for Running Programs Check Return Code $? Get Job Output OUTPUT=`echo “Hello”` OUTPUT=$(echo “Hello”) Send Output Somewhere Redirection:  < ,  > Pipes
Pipes Lots of Little Tools echo “Hello”  |  \ wc -c INPUT echo OUTPUT ERROR 0 1 2 INPUT wc OUTPUT ERROR 0 1 2 A Pipe!
Email Notification % echo “Message” | \ mail –s “Here’s your message” \ [email_address]
Dates % DATESTRING=`date +%Y%m%d` % echo $DATESTRING 20060125 % man date
FTP the Hard Way ftp –n –u server.wfu.edu <<_FTP_ user  username password put FILE _FTP_
FTP with  wget wget \ ftp://user:pass@server.wfu.edu/file wget –r \ ftp://user:pass@server.wfu.edu/dir/
FTP with  curl curl –T upload-file \ -u username:password \ ftp://server.wfu.edu/dir/file
Searching:  grep % grep rayra /etc/passwd % grep –r rayra /etc % grep –r RAYRA /etc % grep –ri RAYRA /etc % grep –rli rayra /etc
Searching:  find %  find /home/borwicjh \ -name ‘*.lis’ [all files matching *.lis] % find /home/borwicjh \ -mtime -1 –name ‘*.lis’ [*.lis, if modified within 24h] % man find
Searching:  locate % locate .lis [files with .lis in path] % locate log [also finds “/var/log/messages”]
Applied Shell Programming
Make Your Life Easier TAB completion Control+R history cd - Study a UNIX Editor
pushd/popd % cd /tmp %  pushd  /var/log /var/log /tmp % cd .. % pwd /var %  popd /tmp
Monitoring processes ps ps –ef ps –u oracle ps –C sshd man ps
“DOS” Mode Files #!/usr/bin/bash^M FTP transfer in ASCII, or dos2unix infile > outfile
sqlplus JOB=“ZZZTEST” PARAMS=“ZZZTEST_PARAMS” PARAMS_USER=“BORWICJH” sqlplus $BANNER_USER/$BANNER_PW << _EOF_ set serveroutput on set sqlprompt &quot;&quot; EXECUTE WF_SATURN.FZ_Get_Parameters('$JOB', '$PARAMS', '$PARAMS_USER'); _EOF_
sqlplus sqlplus $USER/$PASS @$FILE_SQL \ $ARG1 $ARG2 $ARG3 if [ $? –ne 0 ] then exit 1 fi if [  -e /file/sql/should/create  ] then […use SQL-created file…] fi Ask Amy Lamy!  
Passing Arguments % cat > test.sh <<_TEST_ echo “Your name is \ $1  \ $2 ” _TEST_ % chmod +x test.sh % ./test.sh John Borwick ignore-this Your name is John Borwick
INB Job Submission Template $1 : user ID $2 : password $3 : one-up number $4 : process name $5 : printer name % /path/to/your/script $UI $PW \ $ONE_UP $JOB $PRNT
Scheduling Jobs % crontab -l 0 0 * * * daily-midnight-job.sh 0 * * * * hourly-job.sh * * * * * every-minute.sh 0 1 * * 0 1AM-on-sunday.sh %  EDITOR=vi  crontab –e % man  5  crontab
It's Over!
Other Questions? Shells and Shell Scripts bash Running Commands bash  and Banner in Practice

More Related Content

PDF
Intro to Linux Shell Scripting
vceder
 
PDF
Introduction to Kubernetes Workshop
Bob Killen
 
ODP
Linux Introduction (Commands)
anandvaidya
 
PPTX
Github
IFEDAYO ADEYEMI
 
PDF
OpenSync: Open Source for Cloud to Device Enabled Services
All Things Open
 
PPTX
Overview of github
Sangeetha Subramani
 
PDF
Openstack Summit Vancouver 2018 - Multicloud Networking
Shannon McFarland
 
PPTX
Unix shell scripting basics
Manav Prasad
 
Intro to Linux Shell Scripting
vceder
 
Introduction to Kubernetes Workshop
Bob Killen
 
Linux Introduction (Commands)
anandvaidya
 
OpenSync: Open Source for Cloud to Device Enabled Services
All Things Open
 
Overview of github
Sangeetha Subramani
 
Openstack Summit Vancouver 2018 - Multicloud Networking
Shannon McFarland
 
Unix shell scripting basics
Manav Prasad
 

What's hot (20)

PDF
NATS Streaming - an alternative to Apache Kafka?
Anton Zadorozhniy
 
PPTX
A prentation on github
Veronica Ojochona Michael (MCP)
 
PDF
Hashicorp Nomad
Ivan Glushkov
 
PDF
MirrorMaker: Beyond the Basics with Mickael Maison
HostedbyConfluent
 
PPTX
Kubernetes Basics
Antonin Stoklasek
 
PDF
Git
Mayank Patel
 
PDF
Docker by Example - Basics
CodeOps Technologies LLP
 
PPTX
VXLAN Practice Guide
Prasenjit Sarkar
 
PPTX
NGINX High-performance Caching
NGINX, Inc.
 
PDF
Shell scripting
Ashrith Mekala
 
PPTX
Navigating Disaster Recovery in Kubernetes and CNCF Crossplane
Carlos Santana
 
PPTX
High Availability Content Caching with NGINX
NGINX, Inc.
 
PPTX
Cisco nexus series
Anwesh Dixit
 
PDF
Introducing Amazon EKS Anywhere On Apache CloudStack
ShapeBlue
 
PDF
[MeetUp][2nd] 오리뎅이의_쿠버네티스_네트워킹_v1.2
InfraEngineer
 
PPTX
Intro to Helm for Kubernetes
Carlos E. Salazar
 
PDF
API Design, A Quick Guide to REST, SOAP, gRPC, and GraphQL, By Vahid Rahimian
Vahid Rahimian
 
PPTX
Selinux
Mohitgupta8560
 
PDF
Getting up to speed with Kafka Connect: from the basics to the latest feature...
HostedbyConfluent
 
PPTX
Packet Walk(s) In Kubernetes
Don Jayakody
 
NATS Streaming - an alternative to Apache Kafka?
Anton Zadorozhniy
 
A prentation on github
Veronica Ojochona Michael (MCP)
 
Hashicorp Nomad
Ivan Glushkov
 
MirrorMaker: Beyond the Basics with Mickael Maison
HostedbyConfluent
 
Kubernetes Basics
Antonin Stoklasek
 
Docker by Example - Basics
CodeOps Technologies LLP
 
VXLAN Practice Guide
Prasenjit Sarkar
 
NGINX High-performance Caching
NGINX, Inc.
 
Shell scripting
Ashrith Mekala
 
Navigating Disaster Recovery in Kubernetes and CNCF Crossplane
Carlos Santana
 
High Availability Content Caching with NGINX
NGINX, Inc.
 
Cisco nexus series
Anwesh Dixit
 
Introducing Amazon EKS Anywhere On Apache CloudStack
ShapeBlue
 
[MeetUp][2nd] 오리뎅이의_쿠버네티스_네트워킹_v1.2
InfraEngineer
 
Intro to Helm for Kubernetes
Carlos E. Salazar
 
API Design, A Quick Guide to REST, SOAP, gRPC, and GraphQL, By Vahid Rahimian
Vahid Rahimian
 
Getting up to speed with Kafka Connect: from the basics to the latest feature...
HostedbyConfluent
 
Packet Walk(s) In Kubernetes
Don Jayakody
 
Ad

Viewers also liked (11)

PPTX
BMC Control M Advantage
Vyom Labs
 
PPTX
The Power of Simple: Whats New in BMC Control-M 8
BMC Software
 
PPT
Unix/Linux Basic Commands and Shell Script
sbmguys
 
PPT
Shell Scripting in Linux
Anu Chaudhry
 
PDF
Quick start bash script
Simon Su
 
ODP
OpenGurukul : Language : Shell Scripting
Open Gurukul
 
PDF
Unix Shell Scripting
Mustafa Qasim
 
PPT
Basic command ppt
Rohit Kumar
 
PDF
Let us c(by yashwant kanetkar) chapter 2 solution
rohit kumar
 
PPT
Linux command ppt
kalyanineve
 
PPTX
Linux ppt
lincy21
 
BMC Control M Advantage
Vyom Labs
 
The Power of Simple: Whats New in BMC Control-M 8
BMC Software
 
Unix/Linux Basic Commands and Shell Script
sbmguys
 
Shell Scripting in Linux
Anu Chaudhry
 
Quick start bash script
Simon Su
 
OpenGurukul : Language : Shell Scripting
Open Gurukul
 
Unix Shell Scripting
Mustafa Qasim
 
Basic command ppt
Rohit Kumar
 
Let us c(by yashwant kanetkar) chapter 2 solution
rohit kumar
 
Linux command ppt
kalyanineve
 
Linux ppt
lincy21
 
Ad

Similar to Unix Shell Scripting Basics (20)

PPT
Unix Shell Scripting Basics
Sudharsan S
 
PPTX
Raspberry pi Part 25
Techvilla
 
ODP
Perl Moderno
Tiago Peczenyj
 
PDF
PHP Programming and its Applications workshop
S.Mohideen Badhusha
 
PDF
Module 03 Programming on Linux
Tushar B Kute
 
ODP
NYPHP March 2009 Presentation
brian_dailey
 
PPT
Best training-in-mumbai-shell scripting
vibrantuser
 
PDF
Shell scripting
Geeks Anonymes
 
PPT
Php mysql ppt
Karmatechnologies Pvt. Ltd.
 
PPT
2-introduction_to_shell_scripting
erbipulkumar
 
PDF
Unleash your inner console cowboy
Kenneth Geisshirt
 
PDF
Living With Legacy Code
Rowan Merewood
 
PDF
03 tk2123 - pemrograman shell-2
Setia Juli Irzal Ismail
 
PPT
Bioinformatica 29-09-2011-p1-introduction
Prof. Wim Van Criekinge
 
PDF
Interface de Voz con Rails
Svet Ivantchev
 
PPT
course slides -- powerpoint
webhostingguy
 
PPT
Shell Scripts
Dr.Ravi
 
PPTX
Perl basics for Pentesters
Sanjeev Kumar Jaiswal
 
PDF
Git::Hooks
Mikko Koivunalho
 
PPT
Best training-in-mumbai-shell scripting
vibrantuser
 
Unix Shell Scripting Basics
Sudharsan S
 
Raspberry pi Part 25
Techvilla
 
Perl Moderno
Tiago Peczenyj
 
PHP Programming and its Applications workshop
S.Mohideen Badhusha
 
Module 03 Programming on Linux
Tushar B Kute
 
NYPHP March 2009 Presentation
brian_dailey
 
Best training-in-mumbai-shell scripting
vibrantuser
 
Shell scripting
Geeks Anonymes
 
2-introduction_to_shell_scripting
erbipulkumar
 
Unleash your inner console cowboy
Kenneth Geisshirt
 
Living With Legacy Code
Rowan Merewood
 
03 tk2123 - pemrograman shell-2
Setia Juli Irzal Ismail
 
Bioinformatica 29-09-2011-p1-introduction
Prof. Wim Van Criekinge
 
Interface de Voz con Rails
Svet Ivantchev
 
course slides -- powerpoint
webhostingguy
 
Shell Scripts
Dr.Ravi
 
Perl basics for Pentesters
Sanjeev Kumar Jaiswal
 
Git::Hooks
Mikko Koivunalho
 
Best training-in-mumbai-shell scripting
vibrantuser
 

More from Dr.Ravi (20)

PDF
Corporate Overview
Dr.Ravi
 
PDF
Excel For The Ceo
Dr.Ravi
 
PDF
Project Specs Pf
Dr.Ravi
 
PDF
Pf Day5
Dr.Ravi
 
PDF
Assignments Programming Fundamentals
Dr.Ravi
 
PDF
Hdd Chssc
Dr.Ravi
 
PDF
Chssc Day3
Dr.Ravi
 
PDF
Chssc Day1
Dr.Ravi
 
PDF
Pf Day3
Dr.Ravi
 
PDF
Ldd Pf
Dr.Ravi
 
PDF
Chssc Assignments
Dr.Ravi
 
PDF
Chssc Day4
Dr.Ravi
 
PDF
Chssc Day2
Dr.Ravi
 
PPT
Talk Unix Shell Script
Dr.Ravi
 
PPT
Chap06
Dr.Ravi
 
PPT
Airlover 20030324 1
Dr.Ravi
 
PPT
Unix Basics
Dr.Ravi
 
PPT
Unix Lec2
Dr.Ravi
 
PDF
Unix Book
Dr.Ravi
 
PPT
Unix Basics 04sp
Dr.Ravi
 
Corporate Overview
Dr.Ravi
 
Excel For The Ceo
Dr.Ravi
 
Project Specs Pf
Dr.Ravi
 
Pf Day5
Dr.Ravi
 
Assignments Programming Fundamentals
Dr.Ravi
 
Hdd Chssc
Dr.Ravi
 
Chssc Day3
Dr.Ravi
 
Chssc Day1
Dr.Ravi
 
Pf Day3
Dr.Ravi
 
Ldd Pf
Dr.Ravi
 
Chssc Assignments
Dr.Ravi
 
Chssc Day4
Dr.Ravi
 
Chssc Day2
Dr.Ravi
 
Talk Unix Shell Script
Dr.Ravi
 
Chap06
Dr.Ravi
 
Airlover 20030324 1
Dr.Ravi
 
Unix Basics
Dr.Ravi
 
Unix Lec2
Dr.Ravi
 
Unix Book
Dr.Ravi
 
Unix Basics 04sp
Dr.Ravi
 

Recently uploaded (20)

PDF
Automating ArcGIS Content Discovery with FME: A Real World Use Case
Safe Software
 
PDF
Structs to JSON: How Go Powers REST APIs
Emily Achieng
 
PDF
Software Development Company | KodekX
KodekX
 
PDF
A Strategic Analysis of the MVNO Wave in Emerging Markets.pdf
IPLOOK Networks
 
PDF
Beyond Automation: The Role of IoT Sensor Integration in Next-Gen Industries
Rejig Digital
 
PPT
Coupa-Kickoff-Meeting-Template presentai
annapureddyn
 
PPTX
AI and Robotics for Human Well-being.pptx
JAYMIN SUTHAR
 
PDF
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
 
PDF
Data_Analytics_vs_Data_Science_vs_BI_by_CA_Suvidha_Chaplot.pdf
CA Suvidha Chaplot
 
PDF
REPORT: Heating appliances market in Poland 2024
SPIUG
 
PDF
NewMind AI Weekly Chronicles - July'25 - Week IV
NewMind AI
 
PDF
The Evolution of KM Roles (Presented at Knowledge Summit Dublin 2025)
Enterprise Knowledge
 
PDF
This slide provides an overview Technology
mineshkharadi333
 
PDF
Advances in Ultra High Voltage (UHV) Transmission and Distribution Systems.pdf
Nabajyoti Banik
 
PDF
MASTERDECK GRAPHSUMMIT SYDNEY (Public).pdf
Neo4j
 
PDF
Brief History of Internet - Early Days of Internet
sutharharshit158
 
PDF
Tea4chat - another LLM Project by Kerem Atam
a0m0rajab1
 
PDF
Orbitly Pitch Deck|A Mission-Driven Platform for Side Project Collaboration (...
zz41354899
 
PDF
How Open Source Changed My Career by abdelrahman ismail
a0m0rajab1
 
PDF
Research-Fundamentals-and-Topic-Development.pdf
ayesha butalia
 
Automating ArcGIS Content Discovery with FME: A Real World Use Case
Safe Software
 
Structs to JSON: How Go Powers REST APIs
Emily Achieng
 
Software Development Company | KodekX
KodekX
 
A Strategic Analysis of the MVNO Wave in Emerging Markets.pdf
IPLOOK Networks
 
Beyond Automation: The Role of IoT Sensor Integration in Next-Gen Industries
Rejig Digital
 
Coupa-Kickoff-Meeting-Template presentai
annapureddyn
 
AI and Robotics for Human Well-being.pptx
JAYMIN SUTHAR
 
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
 
Data_Analytics_vs_Data_Science_vs_BI_by_CA_Suvidha_Chaplot.pdf
CA Suvidha Chaplot
 
REPORT: Heating appliances market in Poland 2024
SPIUG
 
NewMind AI Weekly Chronicles - July'25 - Week IV
NewMind AI
 
The Evolution of KM Roles (Presented at Knowledge Summit Dublin 2025)
Enterprise Knowledge
 
This slide provides an overview Technology
mineshkharadi333
 
Advances in Ultra High Voltage (UHV) Transmission and Distribution Systems.pdf
Nabajyoti Banik
 
MASTERDECK GRAPHSUMMIT SYDNEY (Public).pdf
Neo4j
 
Brief History of Internet - Early Days of Internet
sutharharshit158
 
Tea4chat - another LLM Project by Kerem Atam
a0m0rajab1
 
Orbitly Pitch Deck|A Mission-Driven Platform for Side Project Collaboration (...
zz41354899
 
How Open Source Changed My Career by abdelrahman ismail
a0m0rajab1
 
Research-Fundamentals-and-Topic-Development.pdf
ayesha butalia
 

Unix Shell Scripting Basics

  • 2. Agenda What is a shell? A shell script? Introduction to bash Running Commands Applied Shell Programming
  • 3. What is a shell? % ▌
  • 4. What is a shell? /bin/bash
  • 5. What is a shell? #!/bin/bash
  • 6. What is a shell? INPUT shell OUTPUT ERROR
  • 7. What is a shell? Any Program But there are a few popular shells…
  • 8. Bourne Shells /bin/sh /bin/bash “Bourne-Again Shell” Steve Bourne
  • 9. Other Common Shells C Shell ( /bin/csh ) Turbo C Shell ( /bin/tcsh ) Korn Shell ( /bin/ksh )
  • 10. An aside: What do I mean by /bin ? C Shell ( /bin/csh ) Turbo C Shell ( /bin/tcsh ) Korn Shell ( /bin/ksh )
  • 11. An aside: What do I mean by /bin ? /bin, /usr/bin, /usr/local/bin /sbin, /usr/sbin, /usr/local/sbin /tmp /dev /home/borwicjh
  • 12. What is a Shell Script? A Text File With Instructions Executable
  • 13. What is a Shell Script? % cat > hello.sh <<MY_PROGRAM #!/bin/sh echo ‘Hello, world’ MY_PROGRAM % chmod +x hello.sh % ./hello.sh Hello, world
  • 14. What is a Shell Script? A Text File % cat > hello.sh <<MY_PROGRAM #!/bin/sh echo ‘Hello, world’ MY_PROGRAM % chmod +x hello.sh % ./hello.sh Hello, world
  • 15. An aside: Redirection cat > /tmp/myfile cat >> /tmp/myfile cat 2> /tmp/myerr cat < /tmp/myinput cat <<INPUT Some input INPUT cat > /tmp/x 2>&1 0 1 2 INPUT env OUTPUT ERROR
  • 16. What is a Shell Script? How To Run % cat > hello.sh <<MY_PROGRAM #!/bin/sh echo ‘Hello, world’ MY_PROGRAM % chmod +x hello.sh % ./hello.sh Hello, world
  • 17. What is a Shell Script? What To Do % cat > hello.sh <<MY_PROGRAM #!/bin/sh echo ‘Hello, world’ MY_PROGRAM % chmod +x hello.sh % ./hello.sh Hello, world
  • 18. What is a Shell Script? Executable % cat > hello.sh <<MY_PROGRAM #!/bin/sh echo ‘Hello, world’ MY_PROGRAM % chmod +x hello.sh % ./hello.sh Hello, world
  • 19. What is a Shell Script? Running it % cat > hello.sh <<MY_PROGRAM #!/bin/sh echo ‘Hello, world’ MY_PROGRAM % chmod +x hello.sh % ./hello.sh Hello, world
  • 20. Finding the program: PATH % ./hello.sh echo vs. /usr/bin/echo % echo $PATH /bin:/usr/bin:/usr/local/bin: /home/borwicjh/bin % which echo /usr/bin/echo
  • 21. Variables and the Environment % hello.sh bash: hello.sh: Command not found % PATH=“$PATH:.” % hello.sh Hello, world
  • 22. An aside: Quoting % echo ‘ $USER ’ $USER % echo “ $USER ” borwicjh % echo “ \” ” ” % echo “deacnet \\ sct” deacnet\sct % echo ‘ \” ’ \”
  • 23. Variables and the Environment % env […variables passed to sub-programs…] % NEW_VAR=“Yes” % echo $NEW_VAR Yes % env […PATH but not NEW_VAR…] % export NEW_VAR % env […PATH and NEW_VAR…]
  • 24. Welcome to Shell Scripting! Shebang! The Environment PATH Input, Output, and Error chmod
  • 25. How to Learn man man bash man cat man man man –k man –k manual Learning the Bash Shell , 2 nd Ed. “ Bash Reference” Cards http://www.tldp.org/LDP/abs/html/
  • 27. Continuing Lines: \ % echo This \ Is \ A \ Very \ Long \ Command Line This Is A Very Long Command Line %
  • 28. Exit Status $? 0 is True % ls /does/not/exist % echo $? 1 % echo $? 0
  • 29. Exit Status: exit % cat > test.sh <<_TEST_ exit 3 _TEST_ % chmod +x test.sh % ./test.sh % echo $? 3
  • 30. Logic: test % test 1 -lt 10 % echo $? 0 % test 1 == 10 % echo $? 1
  • 31. Logic: test test [ ] [ 1 –lt 10 ] [[ ]] [[ “this string” =~ “this” ]] (( )) (( 1 < 10 ))
  • 32. Logic: test [ -f /etc/passwd ] [ ! –f /etc/passwd ] [ -f /etc/passwd –a –f /etc/shadow ] [ -f /etc/passwd –o –f /etc/shadow ]
  • 33. An aside: $(( )) for Math % echo $(( 1 + 2 )) 3 % echo $(( 2 * 3 )) 6 % echo $(( 1 / 3 )) 0
  • 34. Logic: if if something then : # “elif” a contraction of “else if”: elif something-else then : else then : fi
  • 35. Logic: if if [ $USER –eq “borwicjh” ] then : # “elif” a contraction of “else if”: elif ls /etc/oratab then : else then : fi
  • 36. Logic: if # see if a file exists if [ -e /etc/passwd ] then echo “/etc/passwd exists” else echo “/etc/passwd not found!” fi
  • 37. Logic: for for i in 1 2 3 do echo $i done
  • 38. Logic: for for i in /* do echo “Listing $i:” ls -l $i read done
  • 39. Logic: for for i in /* do echo “Listing $i:” ls -l $i read done
  • 40. Logic: for for i in /* do echo “Listing $i:” ls -l $i read done
  • 41. Logic: C-style for for (( expr1 ; expr2 ; expr3 )) do list done
  • 42. Logic: C-style for LIMIT=10 for (( a=1 ; a<=LIMIT ; a++ )) do echo –n “$a ” done
  • 43. Logic: while while something do : done
  • 44. Logic: while a=0; LIMIT=10 while [ &quot;$a&quot; -lt &quot;$LIMIT&quot; ] do echo -n &quot;$a ” a=$(( a + 1 )) done
  • 45. Counters COUNTER=0 while [ -e “$FILE.COUNTER” ] do COUNTER=$(( COUNTER + 1)) done Note: race condition
  • 46. Reusing Code: “Sourcing” % cat > /path/to/my/passwords <<_PW_ FTP_USER=“sct” _PW_ % echo $FTP_USER % . /path/to/my/passwords % echo $FTP_USER sct %
  • 47. Variable Manipulation % FILEPATH=/path/to/my/output.lis % echo $FILEPATH /path/to/my/output.lis % echo ${FILEPATH %.lis } /path/to/my/output % echo ${FILEPATH #*/ } path/to/my/output.lis % echo ${FILEPATH ##*/ } output.lis
  • 48. It takes a long time to become a bash guru…
  • 50. Reasons for Running Programs Check Return Code $? Get Job Output OUTPUT=`echo “Hello”` OUTPUT=$(echo “Hello”) Send Output Somewhere Redirection: < , > Pipes
  • 51. Pipes Lots of Little Tools echo “Hello” | \ wc -c INPUT echo OUTPUT ERROR 0 1 2 INPUT wc OUTPUT ERROR 0 1 2 A Pipe!
  • 52. Email Notification % echo “Message” | \ mail –s “Here’s your message” \ [email_address]
  • 53. Dates % DATESTRING=`date +%Y%m%d` % echo $DATESTRING 20060125 % man date
  • 54. FTP the Hard Way ftp –n –u server.wfu.edu <<_FTP_ user username password put FILE _FTP_
  • 55. FTP with wget wget \ ftp://user:[email protected]/file wget –r \ ftp://user:[email protected]/dir/
  • 56. FTP with curl curl –T upload-file \ -u username:password \ ftp://server.wfu.edu/dir/file
  • 57. Searching: grep % grep rayra /etc/passwd % grep –r rayra /etc % grep –r RAYRA /etc % grep –ri RAYRA /etc % grep –rli rayra /etc
  • 58. Searching: find % find /home/borwicjh \ -name ‘*.lis’ [all files matching *.lis] % find /home/borwicjh \ -mtime -1 –name ‘*.lis’ [*.lis, if modified within 24h] % man find
  • 59. Searching: locate % locate .lis [files with .lis in path] % locate log [also finds “/var/log/messages”]
  • 61. Make Your Life Easier TAB completion Control+R history cd - Study a UNIX Editor
  • 62. pushd/popd % cd /tmp % pushd /var/log /var/log /tmp % cd .. % pwd /var % popd /tmp
  • 63. Monitoring processes ps ps –ef ps –u oracle ps –C sshd man ps
  • 64. “DOS” Mode Files #!/usr/bin/bash^M FTP transfer in ASCII, or dos2unix infile > outfile
  • 65. sqlplus JOB=“ZZZTEST” PARAMS=“ZZZTEST_PARAMS” PARAMS_USER=“BORWICJH” sqlplus $BANNER_USER/$BANNER_PW << _EOF_ set serveroutput on set sqlprompt &quot;&quot; EXECUTE WF_SATURN.FZ_Get_Parameters('$JOB', '$PARAMS', '$PARAMS_USER'); _EOF_
  • 66. sqlplus sqlplus $USER/$PASS @$FILE_SQL \ $ARG1 $ARG2 $ARG3 if [ $? –ne 0 ] then exit 1 fi if [ -e /file/sql/should/create ] then […use SQL-created file…] fi Ask Amy Lamy! 
  • 67. Passing Arguments % cat > test.sh <<_TEST_ echo “Your name is \ $1 \ $2 ” _TEST_ % chmod +x test.sh % ./test.sh John Borwick ignore-this Your name is John Borwick
  • 68. INB Job Submission Template $1 : user ID $2 : password $3 : one-up number $4 : process name $5 : printer name % /path/to/your/script $UI $PW \ $ONE_UP $JOB $PRNT
  • 69. Scheduling Jobs % crontab -l 0 0 * * * daily-midnight-job.sh 0 * * * * hourly-job.sh * * * * * every-minute.sh 0 1 * * 0 1AM-on-sunday.sh % EDITOR=vi crontab –e % man 5 crontab
  • 71. Other Questions? Shells and Shell Scripts bash Running Commands bash and Banner in Practice