13,420
edits
Changes
→INVESTIGATION 2: ADDITIONAL LOOPING STATEMENTS
# Add execute permissions and run this shell script<br>What do you notice?<br><br>We can reduce a line in our shell script by using '''command substitution''' in the for loop instead of using the '''set''' command.<br>Let's demonstrate this in another shell script.<br><br>
# Use a text editor like vi or nano to create the text file called '''for-5.bash''' (eg. <span style="color:blue;font-weight:bold;font-family:courier;">vi for-5.bash</span>)<br>If you are using the nano text editor, refer to notes on text editing in a previous week in the course schedule.<br><br>
# Enter the following lines in your shell script:<br><span style="color:blue;font-family:courier;font-weight:bold;">#!/bin/bash<br>clear<br>echo Here are files in my current directory:"<br>echo<br>for x in $(ls)<br>do<br> echo " $x"<br>done<br></span><br>
# Save your editing session and exit the text editor (eg. with vi: press '''ESC''', then type ''':wx''' followed by '''ENTER''').<br><br>
# Add execute permissions for this shell script and run the shell script<br>What do you notice? Does the output for this shell script differ than '''for-4.bash'''? Why?<br><br>We now want to introduce you to the use of '''error-checking'''.<br><br>
# Run your shell script by issuing: <span style="color:blue;font-weight:bold;font-family:courier;">./for-5.bash </span><br><br>When prompted, enter a letter instead of a number. What happens?<br><br>Let's edit the '''for-5.bash''' shell script to perform '''error-checking''' to <u>force</u> the user to enter a numeric value between 0 and 100.<br><br>'''NOTE:''' The '''while''' statement can be used with the '''test''' command (or a simple linux command or a linux pipeline command) for error checking. In our case, we will use a pipeline command with extended regular expressions. In order to loop while the result is TRUE (not FALSE), you can use the negation symbol (!) to set the test condition to the opposite.<br><br>
# Use a text editor like vi or nano to edit the text file called '''for-5.bash''' (eg. <span style="color:blue;font-weight:bold;font-family:courier;">vi for-5.bash</span>)<br><br>If you are using the nano text editor, refer to notes on text editing in a previous week in the course schedule.<br><br>
# Add the following lines in your shell script <u>AFTER</u> the read statement to prompt the user for a mark:<br><span style="color:blue;font-family:courier;font-weight:bold;"><br>while ! echo $mark | egrep "^[0-9]{1,}$" > /dev/null 2> /dev/null<br>do<br> read -p "Not a valid number. Enter a mark (0-100): " mark<br>done</span><br><br>
# Save your editing session and exit the text editor (eg. with vi: press '''ESC''', then type ''':wx''' followed by '''ENTER''').<br><br>
# Run your shell script by issuing:<br><span style="color:blue;font-weight:bold;font-family:courier;">./for-5.bash</span><br><br>