UNIX Hints & Hacks |
|||||||||||||||||||||||||||||||||||||
Chapter 1: Topics in Administration |
|
||||||||||||||||||||||||||||||||||||
|
This function script counts from and to a range of numbers.
Shell: sh
This script counts between a range of numbers that are passed through STDIN. It is sometimes necessary to generate a range of numbers to be used within a command or another shell script.
#! /bin/sh LO=$1;HI=$2 while [ $LO -le $HI ] do echo -n $LO " " LO=`expr $LO + 1` done
Line 1: Define the shell being used.
Line 3: Set the variable $LO to the first argument passed to STDIN. Set the variable $HI to the second argument passed to STDIN.
Line 5: Process through the range of numbers until $LO is greater than $HI.
Line 7: Output the current number in $LO.
Line 8: Increment the number in $LO.
Line 9: Exit if $LO is greater than $HI; otherwise, continue with the next number in the range.
If the previous script is named count and executed
$ count 4 13 4 5 6 7 8 9 10 11 12 13
the script will count from 4 to 13 without any carriage returns.
This script is very useful. The output from the script can be passed to other scripts to enhance their functionality. Shell scripts do not have the capability to count within a range of numbers. This little function script provides this capability.
As administrators, you are often faced with writing shell scripts that require some kind of loop within them. Performing a loop around a range of numbers can get messy if there is a large range involved. By using the counting script described previously, a lengthy for loop can be shortened to a call to the counting script.
Here is what you have to do when there is no counting script to call:
#! /bin/sh STRING="The quick brown fox jumped really high" for i in `echo "5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20"` do echo $STRING | cut -c$i done
Compare that to this, when the counting script is available:
#! /bin/sh STRING="The quick brown fox jumped really high" for i in `count 5 20` do echo $STRING | cut -c$i done
This script simply prints out each letter between the fifth and twentieth characters in the string on a line by itself. If the script is needed to process a large range of numbers, the first method of counting with an echo command isn't too efficient. This little function script is great for processing strings, characters, files, and directories--there are many possible uses for this script.
UNIX Hints & Hacks |
|||||||||||||||||||||||||||||||||||||
Chapter 1: Topics in Administration |
|
||||||||||||||||||||||||||||||||||||
|
© Copyright Macmillan USA. All rights reserved.