Changes

Jump to: navigation, search

Tutorial12: Shell Scripting - Part 2

No change in size, 10:30, 29 December 2020
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="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>&nbsp;&nbsp;&nbsp;echo " &nbsp;&nbsp;&nbsp;$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><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>
# Use the '''more''' command to view the text file called '''for-5.bash''' (eg. <span style="color:blue;font-weight:bold;font-family:courier;">more for-5.bash</span>)<br><br>Take a few moments to re-familiarize yourself with this shell script<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>
13,420
edits

Navigation menu