SlideShare uma empresa Scribd logo
1 de 14
ICP-1002: ICT Laboratory
Introduction to Linux        Lab 4 – Scripts


           Scripts

           One of the big advantages of a textual command line is that is very easy to link
           programs together. You saw this with pipes.

           Another advantage is that it is easy to control a program non-interactively, this
           makes it easy a control programs from other programs.

           eg. If you wanted to play an mp3 in a GUI mp3 player you might click on the
           mp3 program icon and then choose a file to play, using some 'clicks'. in general
           when you need to click on a program to make it do something, its quite hard to
           do this from your own programs.

           Luckily with a command line mp3 player its very easy, to play an mp3 file you
           might send a command like (eg):

           mp3-player –play='aSong.mp3'

           Sending such a command from a remote program is very easy.

           All of this means linux is a very powerful platform for write short simple
           programs that can use functionality from lots of other command line
           programs.
ICP-1002: ICT Laboratory
Introduction to Linux         Lab 4 – Scripts



           A script in Linux is just a list of commands stored in a file, just like you would
           type them in at the command line.

           It is customary to end a script file with '.sh' so you might call a file:

           backup.sh
           destoyAllData.sh
           launchScript.sh

           You can use the vi editor to create such a file, all that is special about the script
           is the first line which determines which interpretor will run the script. We will
           start by you the 'sh' the 'shell' interpretor. To use sh the first line of the script is

           #!/bin/sh

           another common alternative is 'bash' the 'bourne again shell'.

           #!/bin/bash

           bash has more features like support for array, but for now we will use 'sh'.
ICP-1002: ICT Laboratory
Introduction to Linux          Lab 4 – Scripts



           As mentioned scripts are just list of commands that you could otherwise type in
           to the shell and run, but which instead get run when you run the script.

           The echo command is used to print something in the terminal, as you might
           imagine this is pretty useless outside of scripts. Try it, type:

           echo Hello World!

           you will see the string printed out. In side a script thought, this can be very
           useful as it is the easiest way from you script to send information to the user.

           lets make a example. Create a file called helloWorld.sh with the following two
           lines in:

           #!/bin/sh
           echo Hello World!

           save the file. It's possible to run a script like any command just by typing it's
           name. way to run this file is to type:

           sh ./helloWorld.sh
           run it and see the result
ICP-1002: ICT Laboratory
Introduction to Linux         Lab 4 – Scripts



           Variables

           If you haven't programmed before you may not have heard of variables.
           Variables are symbols (names) in a program that store some data. Commonly
           that data could be a number, like 6, 9, 21.22 etc. or a String (word) like 'Hello',
           'Hi', 'Anhygoel' (welsh for unbelievable), or 'Z7r62'.

           *Strings are stored as ASCII text, where as numbers are either binary integers,
           or binary floating point numbers.

           Variables are called variables because the data they refer to can change.

           x=5

           is a statement the 'sets' the value of 'x' to be five'

           if you had two successive lines

           cash=50
           cash=-40

           then the value of cash would be -40 because the second line 're-sets' it.
ICP-1002: ICT Laboratory
Introduction to Linux         Lab 4 – Scripts



           Comments

           Comments are little notes in your code that are there for humans to read and
           are ignored by the interpretor. Comment lines start with # and anything on the
           rest of the line is the comment and is ignored by the machine.

           To make things a bit less simple there is one exception :)
           The very first line that you tell the machine which interpretor protocol to follow:

           #!/bin/sh

           It looks like a comment but it tells the machine which protocol to use (sh or bash
           or something else). The ! character is a special character to identify this line,
           and the next part is the path to the interpretor.

           #Technically the first line not part of the script.

           So use comments liberally to explain what you code does.
ICP-1002: ICT Laboratory
Introduction to Linux        Lab 4 – Scripts



           Comments

           Here's the hello world program again with comments.

           helloWorld2.sh:

           #!/bin/sh
           #the line above is technically not a comment, but this line is.
           #so it this
           #i can put what every I want here, it doesnt matter
           #blah blah (*(*H(H*IUH^&GYGH
           #the line below is not a comment, is instruction
           echo hello again World!
           #if we had miss spelt echo that line would have made an error.
           #but it dun matta if we spelz da comentz rong
ICP-1002: ICT Laboratory
Introduction to Linux       Lab 4 – Scripts



           Comments

           Generally use comments to explain what parts of a program does, so a better
           commented helloWorld2.sh would be:

           #!/bin/sh

           #prints hello world
           echo hello again World!

           In general a programmer would never comment an echo line, because it is
           obvious to a programmer what an echo line does. Normally a programmer
           would comment a block of code rather than a single line. eg:

           #display the menu
           echo Menu
           echo 1. Load file
           echo 2. Take over world
           echo 3. Quit
ICP-1002: ICT Laboratory
Introduction to Linux      Lab 4 – Scripts



           Comments

           In these labs, the audience for your code is yourself and the marker, so
           comment you code accordingly. If in doubt comment.
           Always comment new commands that you haven't explained in a previous
           exercise/lab.
           Otherwise comment whole blocks of code explaining what they do, where you
           think it is appropriate.
ICP-1002: ICT Laboratory
Introduction to Linux            Lab 4 – Scripts



           #A comment on white space in script files

           Shell scripts are VERY sensitive to white space (space, tab, black lines).

           In general blank lines have no effect, so feel free to use them to space you code out.

           But Spaces and Tabs have a big effect. Shell scripts are very strict and by far the most common
           type of error for beginner is getting the spacing wrong, so try to learn the correct spacing and
           stick to it. Like a machine! :)

           Eg. the Assignment operator (technical name) '=' is not separated from its arguments by space.
           So

           #This line assigns the value 5 to the symbol x.
           x=5

           #This line produces an error
           x=5

           Try this and try to understand the error in case you get in it future.
ICP-1002: ICT Laboratory
Introduction to Linux           Lab 4 – Scripts



           Debugging Errors

           All programmers make mistakes, some more frequently than others. Being able to identify and
           fix a problem quickly is a very important skill for programmers.

           Sometime you will try to run a script and find that several errors in your code. In this case,
           concentrate on fixing the FIRST one as often the subsequent errors will be knock-on effects of
           the first and fixing this will fix the rest, so fix the first and run the program again.

           In general you are given a line number that caused the problem and long with a description of
           the error type.

           Error messages can be cryptic but often when you understand them they offer an explanation
           as to what is going wrong.

           In the case on the previous page, the interpretor finds a symbol on its own (because there is a
           space) x, and thinks it is a command, it doesn't know this command so without looking any
           further it says 'command not found'. If you do x= 2 then the same thing will happen with the 2.
ICP-1002: ICT Laboratory
Introduction to Linux            Lab 4 – Scripts



           EXPR – arithmetic expressions

           Shell scripting is not the most elegant for doing arithmetic expressions. To do arithmetic we use
           the expr command. It takes its arguments separated by spaces. Try these at the command
           prompt:

           expr 2 + 2
           expr 3 * 6 + 2 – 1
           expr 13 % 4

           % also called 'modulo' is often useful in loop conditions. It gives the remainder so in this
           example 4 goes in to 13 3 times, with a remainder of 1. expr 13 % 4 gives the remainder 1.

           in programming languages we often want to use a symbol that is already used for something
           else, this is the case with the * symbol. So for multiplication we put *
           Adding a  like this is known as 'escaping' the * symbol. We have to escape brackets too, so to
           make the expression ((3 + 9 )/ 4) * 12 , we would do:
           expr ( ( 3 + 9 ) / 4 ) * 12

           we use the / for division, but note that expr doesnt do floating point numbers, so 13 / 4 is 3

           Finally when we want to assign the result of an expr expression to a variable, we need to use
           the ` quotes. (these are found to the left of 1 on a standard keyboard) so eg:

           dailyWage=`expr 300 / 7`
           #note no spaces either side of =
           #if you use the wrong quotes this will not work
ICP-1002: ICT Laboratory
Introduction to Linux            Lab 4 – Scripts



           using variables

           When we use a variable in a command, we need to tell the interpretor the following symbol is a
           variable you should substitute in it's value.

           eg try this scripts

           #!/bin/sh
           division=`expr 13 / 4`
           modulus=`expr 13 % 4`
           echo the result of 13 / 4 is $division with a remainder of $modulus
ICP-1002: ICT Laboratory
Introduction to Linux              Lab 4 – Scripts



           read

           We use the read command to read user input, this way your scripts can be interactive.

           the command:

           read userInput

           will cause the execution of the script to stop and wait for the user to type in something, this will
           then be stored in the variable called userInput. You can call it whatever you like.

           eg testInteract1.sh :

           #!/bin/sh
           echo Hello, please enter you name:
           read userInputName
           echo Hello $userInputName, nice chatting to you
ICP-1002: ICT Laboratory
Introduction to Linux            Lab 4 – Scripts



           Exercises

           1. The simplest chat-bot ever.
           Write a script that asks the users for 5 pieces of information. Once all the five pieces of
           information have been read in the script should print out a paragraph showing it has knowledge
            of the 5 pieces of information. The script should comment on the users input in a chatty way.
           Be as creative as you like.

           2. The world most basic calculator
           Write a script that ask for two numbers, the script will then print out the first number divided by
           the second along with any remainder.

           3. An extremely simple word count information utility

           Write a script that ask you for a filename. The script will then print out word count information
           for that file in the current directory.


           Give your scripts suitable names, add comments and submit them in a text document to
           blackboard. Include the exercise number and script file name before each listing.

Mais conteúdo relacionado

Mais procurados

Learn c language Important topics ( Easy & Logical, & smart way of learning)
Learn c language Important topics ( Easy & Logical, & smart way of learning)Learn c language Important topics ( Easy & Logical, & smart way of learning)
Learn c language Important topics ( Easy & Logical, & smart way of learning)Rohit Singh
 
Learning Python for Raspberry Pi
Learning Python for Raspberry PiLearning Python for Raspberry Pi
Learning Python for Raspberry Pianishgoel
 
Listen and look at your PHP code
Listen and look at your PHP codeListen and look at your PHP code
Listen and look at your PHP codeGabriele Santini
 
Solutions manual for absolute java 5th edition by walter savitch
Solutions manual for absolute java 5th edition by walter savitchSolutions manual for absolute java 5th edition by walter savitch
Solutions manual for absolute java 5th edition by walter savitchAlbern9271
 
Programming with \'C\'
Programming with \'C\'Programming with \'C\'
Programming with \'C\'bdmsts
 
Lecture 04 syntax analysis
Lecture 04 syntax analysisLecture 04 syntax analysis
Lecture 04 syntax analysisIffat Anjum
 
Coding in Disaster Relief - Worksheet (Advanced)
Coding in Disaster Relief - Worksheet (Advanced)Coding in Disaster Relief - Worksheet (Advanced)
Coding in Disaster Relief - Worksheet (Advanced)Charling Li
 
Chapter1 Introduction of compiler
Chapter1 Introduction of compiler Chapter1 Introduction of compiler
Chapter1 Introduction of compiler Danish Alam
 
A brief introduction to C Language
A brief introduction to C LanguageA brief introduction to C Language
A brief introduction to C LanguageMohamed Elsayed
 
Programming in C Basics
Programming in C BasicsProgramming in C Basics
Programming in C BasicsBharat Kalia
 
A tutorial introduction to the unix text editor ed
A tutorial introduction to the unix text editor edA tutorial introduction to the unix text editor ed
A tutorial introduction to the unix text editor edHumberto Garay
 
1. introduction to computer
1. introduction to computer1. introduction to computer
1. introduction to computerShankar Gangaju
 
A Quick Taste of C
A Quick Taste of CA Quick Taste of C
A Quick Taste of Cjeremyrand
 
Learning R while exploring statistics
Learning R while exploring statisticsLearning R while exploring statistics
Learning R while exploring statisticsDorothy Bishop
 

Mais procurados (20)

Learn c language Important topics ( Easy & Logical, & smart way of learning)
Learn c language Important topics ( Easy & Logical, & smart way of learning)Learn c language Important topics ( Easy & Logical, & smart way of learning)
Learn c language Important topics ( Easy & Logical, & smart way of learning)
 
Learning Python for Raspberry Pi
Learning Python for Raspberry PiLearning Python for Raspberry Pi
Learning Python for Raspberry Pi
 
Listen and look at your PHP code
Listen and look at your PHP codeListen and look at your PHP code
Listen and look at your PHP code
 
Solutions manual for absolute java 5th edition by walter savitch
Solutions manual for absolute java 5th edition by walter savitchSolutions manual for absolute java 5th edition by walter savitch
Solutions manual for absolute java 5th edition by walter savitch
 
Programming with \'C\'
Programming with \'C\'Programming with \'C\'
Programming with \'C\'
 
SS & CD Module 3
SS & CD Module 3 SS & CD Module 3
SS & CD Module 3
 
Module 2
Module 2 Module 2
Module 2
 
Python Basics
Python BasicsPython Basics
Python Basics
 
Lecture 04 syntax analysis
Lecture 04 syntax analysisLecture 04 syntax analysis
Lecture 04 syntax analysis
 
Coding in Disaster Relief - Worksheet (Advanced)
Coding in Disaster Relief - Worksheet (Advanced)Coding in Disaster Relief - Worksheet (Advanced)
Coding in Disaster Relief - Worksheet (Advanced)
 
Structures
StructuresStructures
Structures
 
Introduction to c programming
Introduction to c programmingIntroduction to c programming
Introduction to c programming
 
Chapter1 Introduction of compiler
Chapter1 Introduction of compiler Chapter1 Introduction of compiler
Chapter1 Introduction of compiler
 
A brief introduction to C Language
A brief introduction to C LanguageA brief introduction to C Language
A brief introduction to C Language
 
Programming in C Basics
Programming in C BasicsProgramming in C Basics
Programming in C Basics
 
Cp week _2.
Cp week _2.Cp week _2.
Cp week _2.
 
A tutorial introduction to the unix text editor ed
A tutorial introduction to the unix text editor edA tutorial introduction to the unix text editor ed
A tutorial introduction to the unix text editor ed
 
1. introduction to computer
1. introduction to computer1. introduction to computer
1. introduction to computer
 
A Quick Taste of C
A Quick Taste of CA Quick Taste of C
A Quick Taste of C
 
Learning R while exploring statistics
Learning R while exploring statisticsLearning R while exploring statistics
Learning R while exploring statistics
 

Semelhante a Lab4 scripts

Shell Scripting and Programming.pptx
Shell Scripting and Programming.pptxShell Scripting and Programming.pptx
Shell Scripting and Programming.pptxHarsha Patel
 
Shell Scripting and Programming.pptx
Shell Scripting and Programming.pptxShell Scripting and Programming.pptx
Shell Scripting and Programming.pptxHarsha Patel
 
basic shell scripting syntex
basic shell scripting syntexbasic shell scripting syntex
basic shell scripting syntexKsd Che
 
L lpic1-v3-103-1-pdf
L lpic1-v3-103-1-pdfL lpic1-v3-103-1-pdf
L lpic1-v3-103-1-pdfhellojdr
 
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 scriptingAkshay Siwal
 
Yeahhhh the final requirement!!!
Yeahhhh the final requirement!!!Yeahhhh the final requirement!!!
Yeahhhh the final requirement!!!olracoatalub
 
Looping and switch cases
Looping and switch casesLooping and switch cases
Looping and switch casesMeoRamos
 
cs3157-summer06-lab1
cs3157-summer06-lab1cs3157-summer06-lab1
cs3157-summer06-lab1tutorialsruby
 
cs3157-summer06-lab1
cs3157-summer06-lab1cs3157-summer06-lab1
cs3157-summer06-lab1tutorialsruby
 
Tutorial basic of c ++lesson 1 eng ver
Tutorial basic of c ++lesson 1 eng verTutorial basic of c ++lesson 1 eng ver
Tutorial basic of c ++lesson 1 eng verQrembiezs Intruder
 
Computer architecture is made up of two main components the Instruct.docx
Computer architecture is made up of two main components the Instruct.docxComputer architecture is made up of two main components the Instruct.docx
Computer architecture is made up of two main components the Instruct.docxbrownliecarmella
 
Linux: Beyond ls and cd
Linux: Beyond ls and cdLinux: Beyond ls and cd
Linux: Beyond ls and cdjacko91
 
Shell Programming_Module2_Part2.pptx.pdf
Shell Programming_Module2_Part2.pptx.pdfShell Programming_Module2_Part2.pptx.pdf
Shell Programming_Module2_Part2.pptx.pdfHIMANKMISHRA2
 
Shell tutorial
Shell tutorialShell tutorial
Shell tutorialVu Duy Tu
 
00 C hello world.pptx
00 C hello world.pptx00 C hello world.pptx
00 C hello world.pptxCarla227537
 
BIT204 1 Software Fundamentals
BIT204 1 Software FundamentalsBIT204 1 Software Fundamentals
BIT204 1 Software FundamentalsJames Uren
 

Semelhante a Lab4 scripts (20)

Shell Scripting and Programming.pptx
Shell Scripting and Programming.pptxShell Scripting and Programming.pptx
Shell Scripting and Programming.pptx
 
Shell Scripting and Programming.pptx
Shell Scripting and Programming.pptxShell Scripting and Programming.pptx
Shell Scripting and Programming.pptx
 
basic shell scripting syntex
basic shell scripting syntexbasic shell scripting syntex
basic shell scripting syntex
 
L lpic1-v3-103-1-pdf
L lpic1-v3-103-1-pdfL lpic1-v3-103-1-pdf
L lpic1-v3-103-1-pdf
 
ForLoops.pptx
ForLoops.pptxForLoops.pptx
ForLoops.pptx
 
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
 
Yeahhhh the final requirement!!!
Yeahhhh the final requirement!!!Yeahhhh the final requirement!!!
Yeahhhh the final requirement!!!
 
Looping and switch cases
Looping and switch casesLooping and switch cases
Looping and switch cases
 
cs3157-summer06-lab1
cs3157-summer06-lab1cs3157-summer06-lab1
cs3157-summer06-lab1
 
cs3157-summer06-lab1
cs3157-summer06-lab1cs3157-summer06-lab1
cs3157-summer06-lab1
 
Tutorial basic of c ++lesson 1 eng ver
Tutorial basic of c ++lesson 1 eng verTutorial basic of c ++lesson 1 eng ver
Tutorial basic of c ++lesson 1 eng ver
 
Computer architecture is made up of two main components the Instruct.docx
Computer architecture is made up of two main components the Instruct.docxComputer architecture is made up of two main components the Instruct.docx
Computer architecture is made up of two main components the Instruct.docx
 
Linux: Beyond ls and cd
Linux: Beyond ls and cdLinux: Beyond ls and cd
Linux: Beyond ls and cd
 
Shell Programming_Module2_Part2.pptx.pdf
Shell Programming_Module2_Part2.pptx.pdfShell Programming_Module2_Part2.pptx.pdf
Shell Programming_Module2_Part2.pptx.pdf
 
Shell tutorial
Shell tutorialShell tutorial
Shell tutorial
 
Lecture 1
Lecture 1Lecture 1
Lecture 1
 
00 C hello world.pptx
00 C hello world.pptx00 C hello world.pptx
00 C hello world.pptx
 
Introduction Of C++
Introduction Of C++Introduction Of C++
Introduction Of C++
 
Presentation 2.ppt
Presentation 2.pptPresentation 2.ppt
Presentation 2.ppt
 
BIT204 1 Software Fundamentals
BIT204 1 Software FundamentalsBIT204 1 Software Fundamentals
BIT204 1 Software Fundamentals
 

Último

Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security ObservabilityGlenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security Observabilityitnewsafrica
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality AssuranceInflectra
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesKari Kakkonen
 
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesMuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesManik S Magar
 
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...itnewsafrica
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsRavi Sanghani
 
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integrationmarketing932765
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Kaya Weers
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Alkin Tezuysal
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI AgeCprime
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Farhan Tariq
 
React Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkReact Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkPixlogix Infotech
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...Wes McKinney
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 

Último (20)

Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security ObservabilityGlenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examples
 
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesMuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
 
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and Insights
 
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI Age
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...
 
React Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkReact Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App Framework
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 

Lab4 scripts

  • 1. ICP-1002: ICT Laboratory Introduction to Linux Lab 4 – Scripts Scripts One of the big advantages of a textual command line is that is very easy to link programs together. You saw this with pipes. Another advantage is that it is easy to control a program non-interactively, this makes it easy a control programs from other programs. eg. If you wanted to play an mp3 in a GUI mp3 player you might click on the mp3 program icon and then choose a file to play, using some 'clicks'. in general when you need to click on a program to make it do something, its quite hard to do this from your own programs. Luckily with a command line mp3 player its very easy, to play an mp3 file you might send a command like (eg): mp3-player –play='aSong.mp3' Sending such a command from a remote program is very easy. All of this means linux is a very powerful platform for write short simple programs that can use functionality from lots of other command line programs.
  • 2. ICP-1002: ICT Laboratory Introduction to Linux Lab 4 – Scripts A script in Linux is just a list of commands stored in a file, just like you would type them in at the command line. It is customary to end a script file with '.sh' so you might call a file: backup.sh destoyAllData.sh launchScript.sh You can use the vi editor to create such a file, all that is special about the script is the first line which determines which interpretor will run the script. We will start by you the 'sh' the 'shell' interpretor. To use sh the first line of the script is #!/bin/sh another common alternative is 'bash' the 'bourne again shell'. #!/bin/bash bash has more features like support for array, but for now we will use 'sh'.
  • 3. ICP-1002: ICT Laboratory Introduction to Linux Lab 4 – Scripts As mentioned scripts are just list of commands that you could otherwise type in to the shell and run, but which instead get run when you run the script. The echo command is used to print something in the terminal, as you might imagine this is pretty useless outside of scripts. Try it, type: echo Hello World! you will see the string printed out. In side a script thought, this can be very useful as it is the easiest way from you script to send information to the user. lets make a example. Create a file called helloWorld.sh with the following two lines in: #!/bin/sh echo Hello World! save the file. It's possible to run a script like any command just by typing it's name. way to run this file is to type: sh ./helloWorld.sh run it and see the result
  • 4. ICP-1002: ICT Laboratory Introduction to Linux Lab 4 – Scripts Variables If you haven't programmed before you may not have heard of variables. Variables are symbols (names) in a program that store some data. Commonly that data could be a number, like 6, 9, 21.22 etc. or a String (word) like 'Hello', 'Hi', 'Anhygoel' (welsh for unbelievable), or 'Z7r62'. *Strings are stored as ASCII text, where as numbers are either binary integers, or binary floating point numbers. Variables are called variables because the data they refer to can change. x=5 is a statement the 'sets' the value of 'x' to be five' if you had two successive lines cash=50 cash=-40 then the value of cash would be -40 because the second line 're-sets' it.
  • 5. ICP-1002: ICT Laboratory Introduction to Linux Lab 4 – Scripts Comments Comments are little notes in your code that are there for humans to read and are ignored by the interpretor. Comment lines start with # and anything on the rest of the line is the comment and is ignored by the machine. To make things a bit less simple there is one exception :) The very first line that you tell the machine which interpretor protocol to follow: #!/bin/sh It looks like a comment but it tells the machine which protocol to use (sh or bash or something else). The ! character is a special character to identify this line, and the next part is the path to the interpretor. #Technically the first line not part of the script. So use comments liberally to explain what you code does.
  • 6. ICP-1002: ICT Laboratory Introduction to Linux Lab 4 – Scripts Comments Here's the hello world program again with comments. helloWorld2.sh: #!/bin/sh #the line above is technically not a comment, but this line is. #so it this #i can put what every I want here, it doesnt matter #blah blah (*(*H(H*IUH^&GYGH #the line below is not a comment, is instruction echo hello again World! #if we had miss spelt echo that line would have made an error. #but it dun matta if we spelz da comentz rong
  • 7. ICP-1002: ICT Laboratory Introduction to Linux Lab 4 – Scripts Comments Generally use comments to explain what parts of a program does, so a better commented helloWorld2.sh would be: #!/bin/sh #prints hello world echo hello again World! In general a programmer would never comment an echo line, because it is obvious to a programmer what an echo line does. Normally a programmer would comment a block of code rather than a single line. eg: #display the menu echo Menu echo 1. Load file echo 2. Take over world echo 3. Quit
  • 8. ICP-1002: ICT Laboratory Introduction to Linux Lab 4 – Scripts Comments In these labs, the audience for your code is yourself and the marker, so comment you code accordingly. If in doubt comment. Always comment new commands that you haven't explained in a previous exercise/lab. Otherwise comment whole blocks of code explaining what they do, where you think it is appropriate.
  • 9. ICP-1002: ICT Laboratory Introduction to Linux Lab 4 – Scripts #A comment on white space in script files Shell scripts are VERY sensitive to white space (space, tab, black lines). In general blank lines have no effect, so feel free to use them to space you code out. But Spaces and Tabs have a big effect. Shell scripts are very strict and by far the most common type of error for beginner is getting the spacing wrong, so try to learn the correct spacing and stick to it. Like a machine! :) Eg. the Assignment operator (technical name) '=' is not separated from its arguments by space. So #This line assigns the value 5 to the symbol x. x=5 #This line produces an error x=5 Try this and try to understand the error in case you get in it future.
  • 10. ICP-1002: ICT Laboratory Introduction to Linux Lab 4 – Scripts Debugging Errors All programmers make mistakes, some more frequently than others. Being able to identify and fix a problem quickly is a very important skill for programmers. Sometime you will try to run a script and find that several errors in your code. In this case, concentrate on fixing the FIRST one as often the subsequent errors will be knock-on effects of the first and fixing this will fix the rest, so fix the first and run the program again. In general you are given a line number that caused the problem and long with a description of the error type. Error messages can be cryptic but often when you understand them they offer an explanation as to what is going wrong. In the case on the previous page, the interpretor finds a symbol on its own (because there is a space) x, and thinks it is a command, it doesn't know this command so without looking any further it says 'command not found'. If you do x= 2 then the same thing will happen with the 2.
  • 11. ICP-1002: ICT Laboratory Introduction to Linux Lab 4 – Scripts EXPR – arithmetic expressions Shell scripting is not the most elegant for doing arithmetic expressions. To do arithmetic we use the expr command. It takes its arguments separated by spaces. Try these at the command prompt: expr 2 + 2 expr 3 * 6 + 2 – 1 expr 13 % 4 % also called 'modulo' is often useful in loop conditions. It gives the remainder so in this example 4 goes in to 13 3 times, with a remainder of 1. expr 13 % 4 gives the remainder 1. in programming languages we often want to use a symbol that is already used for something else, this is the case with the * symbol. So for multiplication we put * Adding a like this is known as 'escaping' the * symbol. We have to escape brackets too, so to make the expression ((3 + 9 )/ 4) * 12 , we would do: expr ( ( 3 + 9 ) / 4 ) * 12 we use the / for division, but note that expr doesnt do floating point numbers, so 13 / 4 is 3 Finally when we want to assign the result of an expr expression to a variable, we need to use the ` quotes. (these are found to the left of 1 on a standard keyboard) so eg: dailyWage=`expr 300 / 7` #note no spaces either side of = #if you use the wrong quotes this will not work
  • 12. ICP-1002: ICT Laboratory Introduction to Linux Lab 4 – Scripts using variables When we use a variable in a command, we need to tell the interpretor the following symbol is a variable you should substitute in it's value. eg try this scripts #!/bin/sh division=`expr 13 / 4` modulus=`expr 13 % 4` echo the result of 13 / 4 is $division with a remainder of $modulus
  • 13. ICP-1002: ICT Laboratory Introduction to Linux Lab 4 – Scripts read We use the read command to read user input, this way your scripts can be interactive. the command: read userInput will cause the execution of the script to stop and wait for the user to type in something, this will then be stored in the variable called userInput. You can call it whatever you like. eg testInteract1.sh : #!/bin/sh echo Hello, please enter you name: read userInputName echo Hello $userInputName, nice chatting to you
  • 14. ICP-1002: ICT Laboratory Introduction to Linux Lab 4 – Scripts Exercises 1. The simplest chat-bot ever. Write a script that asks the users for 5 pieces of information. Once all the five pieces of information have been read in the script should print out a paragraph showing it has knowledge of the 5 pieces of information. The script should comment on the users input in a chatty way. Be as creative as you like. 2. The world most basic calculator Write a script that ask for two numbers, the script will then print out the first number divided by the second along with any remainder. 3. An extremely simple word count information utility Write a script that ask you for a filename. The script will then print out word count information for that file in the current directory. Give your scripts suitable names, add comments and submit them in a text document to blackboard. Include the exercise number and script file name before each listing.