13,420
edits
Changes
no edit summary
=INTRODUCTION TO SHELL SCRIPTINGUSING SED & AWK UTILTIES=
<br>
===Main Objectives of this Practice Tutorial===
:* Plan and create Use the '''sed''' command to '''manipulate text''' contained in a Shell Scriptfile.
:* Explain the purpose of List and explain several '''addresses''' and '''instructions''' associated with the '''she-bang linesed''' contained at the top of a shell scriptcommand.
:* Set Use the '''permissionssed''' and command as a '''executefilter''' a shell scriptwith Linux pipeline commands.
:* Use the '''environmentawk''' and command to '''user-definedmanipulate text''' variables contained in shell scriptsa file.
:* Use List and explain '''comparison operators''Command Substitution', '''variables''' and '''Math Operationsactions''' associated with the '''awk''' in shell scriptscommand.
:* Explain the purpose of the '''$?''' exit status and Use the '''testawk''' command. :* Use '''if''' and '''if-else''' logic statements in shell scripts. :* Use as a '''forfilter''' loop statement with a list in shell scriptsLinux pipeline commands.
<br><br>
|- valign="top" style="padding-left:15px;"
|colspan="2" |Course Notes'''Slides''':<ul><li>Week 11 Lecture 1 Notes:<br> [[Media:ULI101-Week11.1.pdf | PDF]] | [https://ictmatrix.senecacollege.ca/~murraychris.sauljohnson/uli101ULI101/ULI101-Week11.1.pptx PPTX]</li><li>Week 11 Lecture 2 Notes:<br> [[Media:ULI101-Week10Week11.2.pdf | PDF]] | [https://ictmatrix.senecacollege.ca/~murrayjason.saulcarman/uli101slides/ULI101-Week10Week11.2.pptx PPTX]<br></li></ul>
| style="padding-left:15px;" |Shell Scripting'''Text Manipulation:'''* [https://searchdatacenterwww.techtargetdigitalocean.com/definitioncommunity/shelltutorials/the-basics-of-using-the-sed-stream-editor-to-manipulate-text-in-linux Purpose of using the sed utility]* [https://www.digitalocean.com/community/tutorials/how-to-use-the-awk-language-to-manipulate-text-in-script linux Purposeof using the awk utility]
|colspan="1" style="padding-left:15px;" width="30%"|'''Brauer Instructional Videos:'''<ul><li>[https://www.youtube.com/watch?v=kxEP-KUhOSgnpU6S61AIko&list=PLU1b1f-2Oe90TuYfifnWulINjMv_Wr16N&index=5 Bash Shell Scripting - Part 114 Using the sed Utility]</li><li>[https://www.youtube.com/watch?v=cQepf9fY6cE Creating and Running a Shell ScriptOV3XzjDYgJo&list=PLU1b1f-2Oe90TuYfifnWulINjMv_Wr16N&index=13 Using the awk Utility]</li></ul>
|}
= KEY CONCEPTS =
'''Setting Permissions &<span style="color:blue; Running a Shell Scriptfont-weight:bold;font-family:courier;">Syntax: sed [-n] 'address instruction' filename</span>'''
''Examples:''<br><span style="font-familyHow it Works:courier;">'''chmod u+x myscript.bash<br>./myscript.bash<br>/home/username/myscript.bash<br>~/myscript.bash</span>''' ===Using Variables in Shell Scripts===
* The sed command reads all lines in the input file and will be exposed to the expression<br>(i.e. area contained within quotes) one line at a time.
* The expression can be within single quotes or double quotes.
* The expression contains an address (match condition) and an instruction (operation).
* If the line matches the address, then it will perform the instruction.
* Lines will display be default unless the '''–n''' option is used to suppress default display
<br>
'''Address:'''
* Can use a line number, to select a specific line (for example: '''Environment Variables5''')* Can specify a range of line numbers (for example: '''5,7''')* Regular expressions are contained within forward slashes (e.g. /regular-expression/)* Can specify a regular expression to select all lines that match a pattern (e.g '''/^[0-9].*[0-9]$/''') * If NO address is present, the instruction will apply to ALL lines
[[Image:sed.png|right|500px|]]'''User Defined VariablesInstruction:'''*'''Action''' to take for matched line(s)<b>User*Refer to table on right-defined variablesside for list of some</bbr> are variables that can be used in the shell script for '''customizedcommon instructions''' purposes.and their purpose
<br><br>
* The '''Logic Statementsawk'''command reads all lines in the input file and will be exposed to the expression (contained within quotes) for processing. A *The '''logic statementexpression''' is used to determine which Linux commands to be executed based<br>on the result of a condition (i.e. TRUE (zero valuecontained in quotes) or FALSE represents '''selection criteria''', and '''action''' to execute contained within braces '''{}'''* if selection criteria is matched, then action (non-zero value)between braces)is executed. <table align="right"><tr valign="top"><td>[[Image:logic-1.png|thumb|right|250px|Example of using * The '''–F''' option can be used to specify the default '''iffield delimiter''' logic control-flow statement.]](separator) character</td><tdbr>[[Image:loop-1eg.png|thumb|right|250px|Example of using the '''forawk –F”;”''' looping control (would indicate a semi-flow statementcolon delimited input file).]]</td></tablebr>'''Selection Criteria'''
<br>
=INVESTIGATION 1: USING THE SED UTILITY=
<span style="color:red;">'''Loop StatementsATTENTION''': Effective '''May 9, 2022''' - this online tutorial will be required to be completed by '''Friday in week 11 by midnight'''<br>to obtain a grade of '''2%''' towards this course</span><br><br>
'''Perform the Following Steps:'''
# '''Login''' to your matrix accountand confirm you are located in your '''home''' directory.<br><br># Issue a Linux command to create a directory called '''confirm'sed'' you are located in your '''home''' directory.<br><br>We want # Issue a Linux command to create a Bash Shell script <u>change</u> to welcome the user by their ''username'sed''.<br>Let's first provide some useful tips directory and confirm that you are located in terms of selecting an appropriate name for the shell script'''sed''' directory.<br><br># Issue the following linux Linux command to check if your intended shell script namedownload the data.txt file<br>is already exists ('''copy and paste''' to be run automatically from the Bash shellsave time):<br><span style="color:blue;font-weight:bold;font-family:courier;">which hellowget <nowiki>https://ict.senecacollege.ca/span>~murray.saul/uli101/data.txt<br/nowiki><br/span>You should notice that there is no output and therefore, this shell script name CAN be used.<br><br># Use a Issue the '''text editormore''' like command to quickly view the contents of the '''vidata.txt''' or file.<br>When finished, exit the more command by pressing the letter <span style="color:blue;font-weight:bold;font-family:courier;">q</span>[[Image:sed-1.png|thumb|right|300px|Issuing the '''nanop''' to create instruction without using the text file called '''hello-n'''option (to suppress original output) will display lines twice.]]<br><br>If you are using The '''p''' instruction with the nano text editor, refer '''sed''' command is used to notes on <br>'''print''' (i.e. ''display'') the contents of a text editing in a previous week in the course schedulefile.<br><br># Enter Issue the following two lines in your shell script, replacing "your-username" with your actual nameLinux command:<br><span style="color:blue;font-familyweight:courierbold;font-weightfamily:boldcourier;">echo<br>echo "Hello $USER"<br>echosed 'p' data.txt</span><br><br>'''NOTE:You should notice that each line appears twice''' .<br><br>The variable called reason why standard output appears twice is that the sed command<br>(without the '''USER-n option''' is ) displays all lines regardless of an address used.<br><br>We will use '''environmentpipeline commands''' variable that contains to both display stdout to the current user's login name.<Br>In this way if you wanted screen and save to share your shell script with other users, when they run the shell scriptfiles<br>it will greet by for <u>theirconfirmation</u> username. Using of running these pipeline commands when run a ''environment variables'checking-script' makes your shell script to be more "usable" by others'' later in this investigation.<br><br># Save your editing session and exit Issue the text editorfollowing Linux pipeline command:<br><span style="color:blue;font-weight:bold;font-family:courier;">sed -n 'p' data.txt | tee sed-1.txt</span><br><br>What do you notice? You should see only one line.<br><br>Instead of issuing You can specify an '''address''' to display lines using the sed utility<br>(eg. ''line #''bash, ''' command followed by your shell script pathname as an line #s''' or range of '''line #s'argument'',).<br><br># Issue the following Linux pipeline command:<br>let<span style="color:blue;font-weight:bold;font-family:courier;">sed -n 's simply run it by its filename1 p' data.txt | tee sed-2. This is txt</span><br><br>You should see the most common method first line of running shell scriptsthe text file displayed.<br>What other command is used to only display the first line in a file?<br><br>[[Image:hello1sed-2.png|thumb|right|150px500px|Output of Using the sed command from running your to display a '''hellorange''' shell script (YourUserID is your username)of lines.]]# Issue the following linux Linux pipeline command to run your shell script in your current directory:<br><span style="color:blue;font-weight:bold;font-family:courier;">sed -n '2,5 p' data./hellotxt | tee sed-3.txt</span><br><br>What is displayed? How would you modify the sed command to display the line range 10 to 50?<br><br>The '''You should s''' instruction is used to '''substitute''' text<br>(a similar to method was demonstrated in the vi editor in tutorial 9).<br><br># Issue the following Linux pipeline command:<br><span style="color:blue;font-weight:bold;font-family:courier;">sed '2,5 s/TUTORIAL/LESSON/g' data.txt | tee sed-4.txt | more</span><br><br>What do you notice an error indicating you don't have permissions ? View the original contents of lines 2 to run 5 in the file'''data.txt''' file<br>You need in another shell to first add confirm that the substitution occurred.<br><br>[[Image:sed-3.png|thumb|right|500px|Using the sed command with the '''execute permissions-q''' prior option to running display up to a line number, then quit.]]The '''q''' instruction terminates or '''quits''' the execution of the shell scriptsed utility as soon as it is read in a particular line or matching pattern.<br><br># Issue the following linux Linux pipeline command to add execute permissions for your shell script:<br><span style="color:blue;font-weight:bold;font-family:courier;">chmod sed '11 q' data.txt | tee sed-5.txt</span><br><br>What did you notice? How many lines were displayed<br>before the sed command exited?<br><br>You can use '''regular expressions''' to select lines that match a pattern. In fact,<br>the sed command was one of the <u+x hello>first</u> Linux commands that used regular expression.<br><br>The rules remain the same for using regular expressions as demonstrated in '''tutorial 9'''<br>except the regular expression must be contained within '''forward slashes'''<br>(eg. <span style="font-family:courier;font-weight:bold;">/regexp/</span>).<br><br>[[Image:sed-4.png|thumb|right|400px|Using the sed command using regular expressions with '''anchors'''.]]# Re-run your shell scriptIssue the following Linux pipeline command: <br><span style="color:blue;font-weight:bold;font-family:courier;">sed -n '/^The/ p' data./hellotxt | tee sed-6.txt</span><br><br>Did What do you shell script runnotice?<br><br># Issue the following Linux pipeline command:<br><span style="color:redblue;font-weight:bold;font-family:courier;">sed -n '/d$/ p' data.txt | tee sed-7.txt</span><br><br>What do you notice?<br><br>The '''ATTENTION:sed''' Students will get FRUSTRATED when performing their utility can also be used as a '''assignment 3filter''' when their Bash shell scripts have errorsto manipulate text that<br>was generated from Linux commands.<br><br>[[Image:sed-5. One major cause is png|thumb|right|400px|Using the the OUTPUT of their Bash shell script when run does not sed command with '''EXACTLY matchpipeline''' commands.]]# Issue the required output for the correct Bash shell scriptfollowing Linux pipeline command:<br><span style="color:blue;font-weight:bold;font-family:courier;">who | sed -n '/^[a-m]/ p' | tee sed-8. This requires that txt | more</span><br><br>What did you CAREFULLY notice?<br><br># Issue the following Linux pipeline command:<br><span style="color:blue;font-weight:bold;font-family:courier;">ls | sed -n '/txt$/ p''read''' the requirements of your Bash shell script and create it to the EXACT specifications| tee sed-9.txt</span><br><br>What did you notice?<br><br># Issue the following Linux command to run a checking script:<br><span style="color:blue;font-weight:bold;font-family:courier;">bash /home/murray.saul/myscripts~uli101/week10week11-check-1</span><br><br># If you encounter errors, make corrections and '''re-run''' the checking script until you<br>until you receive a congratulations message, then you can proceed.<br><br>::In the next investigation, you will learn to create and run shell scripts that<br >use variables, positional and special parameters. You will also learn how to<br><u>add</u> a '''she-bang line''' at the top of a shell script to force it to run in a specified shell.<br><br>Proceed to the next investigation.<br><br>
=INVESTIGATION 2: USING THE AWK UTILITY =
In this investigation, you will learn how to use the awk utility to manipulate text and generate reports.
'''Perform the Following Steps:'''
# Confirm that Change to your '''home''' directory and issue a command to '''confirm'''<br>you are located in your '''home''' directory in your Matrix account.<br><br># Use Issue a text editor Linux command to edit the shell script create a directory called '''helloawk'''<br><br># Add the following line Issue a Linux command to the <u>bottomchange</u> of to the file:<br><span style="font-family:courier;font-weight:bold;">echo "The current shell '''awk''' directory and confirm you are using is: $(ps -o cmd= -p $$|cut -dlocated in the '''awk'' ' -f1)"directory.</spanbr><br>Let's download a database file that contains information regarding classic cars.<br><br># Issue the following linux command ('''NOTE:copy and paste''' This command displays the '''name''' of the ''shell'' that the shell script is running in.to save time):<br>The command within <span style="color:blue;font-familyweight:courierbold;font-weightfamily:boldcourier;">$( )wget <nowiki>https://ict.senecacollege.ca/~murray.saul/uli101/cars.txt</nowiki></span> uses a technique known as '''command substitution'''.<br<br><br># Issue the following linux '''cat''' command to change to quickly view the contents of the '''Bourne Shellcars.txt''':file.<br><span style=br>The "color:blue;font-weight:bold;font-family:courier;'''print'''"action (command) is the <u>shdefault</spanu>action of awk to print<br><br>You should notice your shell prompt changed all selected lines that indicates that you are in match a different shell'''pattern'''.<br><br>[[Image:hello2.png|thumb|right|275px|Changing the Bourne shell and running shell script This '''action''' (contained in braces) can provide more options<br>such as printing '''withoutspecific fields''' of selected lines (or records) from a '''She-bang''' linedatabase.<br><br>[[Image:awk-1.png|thumb|right|400px|Using the awk command to display matches of the pattern '''ford'''.]]# Issue the following linux command all to run your shell script display all lines (i.e. records) in the ''Bourne Shell'cars.txt''' database that matches the pattern (or "make") called '''ford''':<br><span style="color:blue;font-weight:bold;font-family:courier;">awk '/ford/ {print}' cars./hellotxt</span><br><br>You should see that you are currently running the shell script "We will use '''shpipeline commands'''" that represents to both display stdout to the '''Bourne shell'''.screen and save to files for <bru>confirmation<br/u>of running these pipeline commands when run a '''NOTE:'checking-script'' Due to the fact that shells (and their features) have '''evolved''' over a period of time,later in this investigation.<br><br>an error may occur if you include a '# Issue the following linux pipeline command all to display records<br>in the '''cars.txt'NEWER'' shell feature database that contain the pattern (i.e.g. make) '''ford'Bash Shell'') in your shell script,:<br>but run it in an ''OLDER<span style="color:blue;font-weight:bold;font-family:courier;">awk '/ford/' shell (ecars.g. ''Bourne Shell'')txt | tee awk-1.txt</span><br><br>What do you notice? You can add a should notice ALL lines displayed <u>without</u> using '''special commentsearch criteria''' to the BEGINNING of the .<ubr>FIRST line</u> of your shell script to<br>You can use ''builtin'force''' it to run in 'variables''' with the shell you want (for example: the Bash shell)'''print''' command for further processing.<br>We will discuss the following variables in this tutorial:<br> # Edit your '''hello''' shell script using a text editor.<br><br># [[Image:awk-2.png|thumb|right|400px|Using the awk command to print search results by '''Insertfield number''' the following line at the .]]'''beginning$0''' of the - Current record (entire line)<br>'''first$1''' line of your hello file:- First field in record<br>'''$n''' - nth field in record<span style="font-family:courier;fontbr>'''NR''' -weight:bold;">#!/bin/bash</span>Record Number (order in database)<br><br>This is referred to as a '''sheNF''' -bang line'''. It forces this script to be run Number of fields in the '''Bash Shell'''.current record<br><br>When For a listing of more variables, please consult your Bash Shell script finishes execution, you are returned to your current shell that you are using<br>(which in our case in Matrix, is still the Bash shell)course notes.<br><br>[[Image:hello3.png|thumb|right|275px|Changing # Issue the following linux pipeline command to display the Bourne shell and running shell script '''withmodel''', '''year''' a , '''She-bangquantity''' line (forcing script to run and price<br>in the '''Bashcars.txt''' shell).]]# database for makes of '''Savechevy''' your editing changes and '''exit''' your text editor.<br><br># While in the Bourne shell, issue the following linux command:<br><span style="color:blue;font-weight:bold;font-family:courier;">awk '/chevy/ {print $2,$3,$4,$5}' cars./hellotxt | tee awk-2.txt</span><br><br>You should notice Notice that the shell name is running in the a '''Bash shellspace'''.is the delimiter for the fields that appear as standard output.<br><br> # It is a good idea to rename your shell script to include an The '''extensiontilde character''' to<br>explain that this is '''Bash Shell script~''' file (referred is used to as search for a "''portable Bash shell script''")pattern or display standard output for a particular field. <br><br># Issue the following linux pipeline command to rename your shell script file:<br><span style="color:blue;font-weight:bold;font-family:courier;">mv hello hello.bash</span>display all '''plymouths''' ('''plym''')<br><br># Run your renamed shell script for confirmation by issuingby '''model name''', '''price''' and '''quantity''':<br><span style="color:blue;font-weight:bold;font-family:courier;">.awk '$1 ~ /helloplym/ {print $2,$3,$4,$5}' cars.bashtxt | tee awk-3.txt</span><br><br># Enter the following linux command to You can also use '''exitcomparison operators''' the ''Bourne shell'' and return to your ''Bash shell'':to specify conditions for processing with matched patterns<br>when using the awk command. Since they are used WITHIN the awk expression,<br><span style="color:blue;font-weight:bold;font-family:courier;">exit</span>they are not confused with redirection symbols<br><br>Let's use some ''[[Image:awk-3.png|thumb|right|400px|Using the awk command to display results based on 'ENVIRONMENT variables''' in our Bash Shell script.<br><br># Use a text editor to edit the shell script called comparison operators'''hello.bash]]'''<''' Less than<br>'''<=''' Less than or equal<br># Add the following lines to the <u'''>bottom</u> of the file:''' Greater than<br><span style'''>="font-family:courier''' font-weight:bold "Greater than or equal<br>echo'''==''' Equal<br>echo "The current directory location is: $PWD"'''!=''' Not equal<br>echo "The current user home directory is: $HOME"<br>echo</span><br><<br># Save your editing changes and exit your text editor.<br><br># Run your renamed shell script for confirmation by issuing:<br><Issue the following linux pipeline command to display display the '''car make''', '''model''', '''quantity''' and '''price''' of all vehicles whose '''prices are less than $5,000''':<br><span style="color:blue;font-weight:bold;font-family:courier;">awk '$5 < 5000 {print $1,$2,$4,$5}' cars./hello.bashtxt | tee awk-4.txt</span><br><br>Take time to view the output and the values of the environment variables.<br>What do you notice?<br><br># Issue the following linux pipeline command to add your current directory to the display display '''PATHprice''' environment variable:,<br><span style="color:blue;font-weight'''quantity''', '''model''' and '''car make''' of vehicles whose '''prices are less than $5,000''':bold;font<br><span style="color:blue;font-weight:bold;font-family:courier;">PATH=awk '$PATH:.5 </span><br5000 {print $5,$4,$2,$1}' cars.txt | tee awk-5.txt</span><br>[[Image:hello4.png|thumb|right|330px|Running <ubr>modified</u> '''hello.bash''' Bash shell script by entering by '''filename''' only.]]# # Issue the following linux pipeline command to confirm that display the current directory '''"."car make''' has been added to ,<br>'''year''' and '''quantity''' of cars that '''begin''' with the '''PATHletter 'f'''' environment variable:<br><span style="color:blue;font-weight:bold;font-family:courier;">echo awk '$PATH<1 ~ /^f/span>{print $1,$2,$4}' cars.txt | tee awk-6.txt<br/span><br># Issue the following to run your Bash shell script just by name:<br><span style="color[[Image:blue;fontawk-weight:bold;font-family:courier;">hello4.bash</span><br>png|thumb|right|400px|Using the awk command to display combined search results based on '''compound operators'''.]]Combined pattern searches can be made<br>Did your Bash shell script run?by using '''compound operator''' symbols:<br><br># Exit your Matrix session, '''&&''' (and log back into your Matrix session.)<br><br># Re-run the '''hello.bash||''' shell script by just using the name. (or)<br><br>What did you notice?<br><br>The setting of # Issue the following linux pipeline command to list all '''PATHfords''' environment variable only worked in the current session only.<br>If you exit the current Matrix sessionwhose '''price is greater than $10, then the recently changed settings for environment variables will be lost.000''':<br>You will in a <u>future</uspan style="color:blue;font-weight:bold;font-family:courier;"> tutorial how to set environment variables in awk '$1 ~ /ford/ && $5 > 10000 {print $0}''startcars.txt | tee awk-up''' files7.txt</span><br><br># Issue the following linux command ('''copy and paste''' to save time):<br><span style="color:redblue;"font-weight:bold;font-family:courier;">wget <nowiki>'''ATTENTIONhttps:''' Students will get FRUSTRATED when performing their '''assignment 3''' when their Bash shell scripts have errors//ict. One major cause is the senecacollege.ca/~murray.saul/uli101/cars2.txt</nowiki></span><br><br># Issue the OUTPUT of their Bash shell script when run does not '''EXACTLY matchcat''' command to quickly view the required output for contents of the correct Bash shell script. This requires that you CAREFULLY '''readcars2.txt''' the requirements of your Bash shell script and create it to the EXACT specifications</span>file.<br><br># Issue the following Linux linux pipeline command to run a checking script:display the '''year'''<br><span style="color:blue;font-weightand '''quantity''' of cars that '''begin''' with the '''letter 'f'''' for the '''cars2.txt''' database:<br><span style="color:boldblue;font-weight:bold;font-family:courier;">bash awk '$1 ~ /home^f/murray{print $2,$4}' cars2.saul/myscripts/week10txt | tee awk-check-2 | more8.txt</span><br><br>If What did you encounter errors, make corrections and notice?<br><br>The problem is that the '''cars2.txt'''redatabase separates each field by a semi-runcolon (''';' the checking script until you<br>receive a congratulations message, then you can proceed.'') <bru>instead<br/u>Let's create a Bash shell script that contain of '''user-created variablesTAB'''.<br><br># Use a text editor to create a Bash shell script called '''user-variablesTherefore, it does not recognize the second and fourth fields.bash'''<br><br># Add the following lines You need to issue awk with the beginning of -F option to indicate that this file:'s fields are separated (delimited) by a semi-colorn.<br><span style="font-family:courier;font-weight:bold;"br>#!/bin/bashIssue the following linux pipeline command to display the '''year'''<br>read -p "Enter your Full Name: " name<br>read -p "Enter your age (in years)and '''quantity''' of cars that '''begin''' with the '''letter 'f'''' for the '''cars2.txt''' database: " age<br>echo <span style="Hello $name color:blue;font-weight:bold;font- You are $age years oldfamily:courier;"</span><brawk -F";" '$1 ~ /^f/ {print $2,$4}' cars2.txt | tee awk-9.txt</span><br># Save your editing changes and exit your text editor.<br>What did you notice this time?<br>[[Image<br># Issue the following to run a checking script:<br><span style="color:userblue;font-variable1.png|thumb|right|300px|Prompting user to enter data via the '''read weight:bold;font-family:courier;">~uli101/week11-p''' command storing into '''usercheck-created variable'''.]]# Issue the 2</span><br><br>If you encounter errors, make corrections and '''chmodre-run''' command to add '''execute permissions''' for the user for the '''user-variables.bash''' file.the checking script until you<br><br># Issue the following to run the user-variables.bash Bash shell script:<br><span style="color:blue;font-weight:bold;font-family:courier;">./user-variables.bash</span><br><br>What did you notice?<br><br># Use a text editor to '''modify''' your Bash shell script called '''user-variables.bash'''<br><br># '''Insert''' the following lines immediately <u>'''below'''</u> the '''she-bang''' line:<br><span style="font-family:courier;font-weight:bold;">age=25<br>readonly age</span><br><br># Save your editing changes and exit your text editor.<br><br>[[Image:user-variable2.png|thumb|right|330px|Trying to change the value of a '''read-only''' variable'''.]]# Issue the following to run the user-variables.bash Bash shell script:<br><span style="color:blue;font-weight:bold;font-family:courier;">./user-variables.bash</span><br><br>What do you notice when you try to change the age variable? Why?<br><br>Let's use '''positional parameters''' and '''special parameters''' in a Bash shell script.<br><br># Use a text editor to create a file called '''parameters.bash'''<br><br># Add the following lines to the beginning of this file:<br><span style="font-family:courier;font-weight:bold;">#!/bin/bash<br>echo \$0: $0<br>echo \$2: $2<br>echo \$3: $3<br><br>echo \$#: $#<br>echo \$*: $*<br><br>shift 2<br>echo \$#: $#<br>echo \$*: $*</span><br><br># Save your editing changes and exit your text editor.<br><br>Notice how the quoting character "'''\'''" is used to display positional parameters like "'''$2'''"<br>as opposed to the value stored in the <u>second</u> positional parameter.<br><br># Issue the '''chmod''' command to add '''execute permissions''' for the user for the '''parameters.bash''' file.<br><br>[[Image:parameter1.png|thumb|right|250px|Results from running shell script (with arguments) that use '''positional parameters''' and '''special parameters'''.]]# Issue the following to run the '''user-variables.bash''' Bash shell script:<br><span style="color:blue;font-weight:bold;font-family:courier;">./parameters.bash</span><br><br>What happened?<br><br>The values for some of the ''positional parameters'' and ''special parameters'' may NOT be<br>displayed properly since you did NOT provide any '''arguments''' when <u>running</u> your Bash shell script.<br><br># Issue the following to run the user-variables.bash Bash shell script with arguments:<br><span style="color:blue;font-weight:bold;font-family:courier;">receive a congratulations message, then you can proceed./parameters.bash 1 2 3 4 5 6 7 8</span><br><br>What do you notice?<br><br>Take some time to view the results and how the ''parameters'' have changed when using the '''shift''' command. <br>
= LINUX PRACTICE QUESTIONS =
Your instructor may take-up these questions during class. It is up to the student to attend classes in order to obtain the answers to the following questions. Your instructor will NOT provide these answers in any other form (eg. e-mail, etc).
''For example'Part A:Display Results from Using the sed Utility'''
<pre>
Line one.
This is the second line.
This is the third.
This is line four.
Five.
Line six follows
Followed by 7
Now line 8
and line nine
Finally, line 10
</pre>
# <span style="font-family:courier;font-weight:bold">sed -n '3,6 p'~murray.saul/uli101/stuff.txt</span><br><br># <span style="font-family:courier;font-weight:bold">sed 'Math Operations4 q'~murray.saul/uli101/stuff.txt</span><br><br># <span style="font-family:courier;font-weight:bold">sed '/the/ d'~murray.saul/uli101/stuff.txt</span><br><br># <span style="font-family:courier;font-weight:bold">sed 's/line/NUMBER/g' ~murray.saul/uli101/stuff.txt</span>
# Write a Linux sed command to display only lines 5 to 9 for the file:In '''~murray.saul/uli101/stuff.txt'''<br><br># Write a Linux sed command to display only lines the begin the pattern “and” for the file: '''~murray.saul/uli101/stuff.txt'''<br><br># Write a Linux sed command to display only lines that end with a digit for the next investigation, you will use file: '''control-flow statements~murray.saul/uli101/stuff.txt''' <br><br># Write a Linux sed command to allow your shell scripts save lines that match the pattern “line” (upper or lowercase) for the file: '''~murray.saul/uli101/stuff.txt''' and save results (overwriting previous contents) to perform differently under different situations: '''~/results.txt'''<br><br>
Note the contents from the following tab-delimited file called '''~murray.saul/uli101/stuff.txt''':
(this file pathname exists for checking your work)
<pre>
Line one.
This is the second line.
This is the third.
This is line four.
Five.
Line six follows
Followed by 7
Now line 8
and line nine
Finally, line 10
</pre>
'''Part D: Writing Linux Commands Using the awk Utility'''
# Write a Bash shell script that clears Linux awk command to display all records for the screen and displays the text Hello World on the screenfile: '''~/cars''' whose fifth field is greater than 10000.<br><br>What permissions are required to run this Bash shell script?<br><br>What are the different ways that you can run this Bash shell script from the command line?<br><br># Write a Bash shell script that clears Linux awk command to display the screen, prompts the user first and fourth fields for their '''full name''' and then prompts the user for their file: '''age~/cars''',<br>then clears the screen again and welcomes the user by their name and tells them their agewhose fifth field begins with a number.<br><br>What comments would you add to the above script’s contents to properly document this Bash shell script to be understood<br>for those users that would read / edit this Bash shell script’s contents?<br><br># Write a Bash shell script that will first set Linux awk command to display the value of a variable called '''number''' to '''23''' second and make this variable third fields for the file: '''read-only~/cars'''.<br>Then the script will clear the screen and prompt the user to enter a value for records that variable called number to another value.<br>Have the script display match the value of the variable called number to prove that it is a read-only variablepattern “chevy”.<br><br>When you ran this Bash shell script, did you encounter an error message?<br>How would you run this Bash shell script, so the error message was NOT displayed?<br><br># Write a Bash shell script that will clear Linux awk command to display the screen first and then display second fields for all arguments that were entered after your Bash shell script when it was run. Also have the Bash shell script display records contained in the number of arguments that were entered after your Bash shell script.<br>file: '''~/cars'''<br><br>
[[Category:ULI101]]