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

Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
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
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
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
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAndikSusilo4
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 

Último (20)

Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
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
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
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
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & Application
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 

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.