shell script loops

From john@superdawg.site Mon Aug  2 23:18:42 2004

Syntax of Conditional Statements
---------------------------------

The following are examples of basic syntax for conditional statements in Korn/Bash shell scripts.

Some examples are quite lame and will require a good imagination, or programming skills, in order to use
these in the real world.  :)


---------------
if statement:
---------------

		if [[ condition ]]
			then
			statements
		elif [[ condition ]]
			then statements
		else
			statements
		fi

-------------------------------------
or more typically:

		if [[ condition ]]; then
			statements
		
		elif [[ condition ]]; then
			statements
		
		else
			statements
		fi

-----------------------------------------------------------
note: the "else" and "elif"  are optional, but recommended.
-----------------------------------------------------------

#!/bin/ksh

VAL=""
# note: VAL is not set so the test below will fail.

print "VAL is ${VAL}"
if [ ${VAL} = YES ]; then
        print 'VAL is set\n'
fi
------------------------------------------------
The following test works:

	VAL=""

	print "VAL is ${VAL}"
	if [[ ${VAL} = YES ]]; then
	        print 'VAL is set\n'
	fi
------------------------------------------------

---------------
FOR statement:
---------------
	for item in list
	do
		statements that use $item
	done

---------------
WHILE statement:
---------------
	while [[ condition ]]
	do
		statements
	done

---------------
CASE statement:
---------------
	case expression in
		pattern1)
			statements;;
		pattern2)
			statements;;
	esac
 
---------------
UNTIL statement:
---------------
	until [[ condition ]]
	do
		statements
	done


---------------------------------------
note:  a file may be created by typing:
	cat > filename
anything typed after that will be put into that filename
until you hit "ctrl D".  

Of course the best plan is to use vi to create a file, 
that way you have editing capabilities.  
So it's a much better practice to type:
	vi filename                          
---------------------------------------


---------------------------------------
Using the "if" statement
---------------------------------------
#!/bin/ksh
# filename: showif
#
#  lame example showing how to use the if statement in a script
#   see the following command line examples for output
# 
#   
print "   Showing the if statement in shell scripts"

if [[ $1 = "" ]]; then
	print "enter at least one argument, please!"
	exit 1      #  Exits script at this point
	# comments are allowed anywhere - exit 1 indicates an exit status
	#   a "0" indicates success where any other value indicates an "error"
	#  the exit status may be tested with the "$?" variable.
fi

if [[ "$#" -lt 3 ]]; then
	print "You entered less than three arguments!"
	# tests the number of the positional parameters (ex below reveals one entered)
fi

if [[ $1 = show ]]; then
	print "You asked me to show you this line"
	# how in the world is the user to know this?  Unless of course they read the script...
else
	print "Okay! I show you nothing."
	#  don't you love programs with attitude?  
fi

---------------------------------------------
-->showif
   Showing the if Statement in Shell Scripts
You must enter at least one argument!!!!

-->showif test
   Showing the if Statement in Shell Scripts
You entered less than three arguments!!
Okay! I show you nothing

-->showif show the line of data
   Showing the if Statement in Shell Scripts
You asked me to show you this line 

------------------------------------------------------


----------------------------
Using the "for" statement
----------------------------

#!/bin/ksh
# filename: showfor
#
print "Showing the for Statement in Shell Scripts"

for args in "$*"
do
	print "The \$* argument = $args"
done

for args in "$@"
do
	print "The \$@ argument = $args"
done

for birds in parrot robin lark
do
	print "The bird listed = $birds"
done

for FILES in $(ls /etc/rc*)
do
	print "The file listed in /etc/rc = $FILES"
done
------------------------------------------------------
-->showfor this is a test | more
Showing the for Statement in Shell Scripts
The $* argument = this is a test
The $@ argument = this
The $@ argument = is
The $@ argument = a
The $@ argument = test
The bird listed = parrot
The bird listed = robin
The bird listed = lark
The file listed in /etc = /etc/rc0
The file listed in /etc = /etc/rc1
The file listed in /etc = /etc/rc2
The file listed in /etc = /etc/rc3
The file listed in /etc = /etc/rcS
The file listed in /etc = /etc/rc.d:
The file listed in /etc = /etc/rc0.d:
The file listed in /etc = K00ANNOUNCE
The file listed in /etc = K01DOWN
The file listed in /etc = K20lp
The file listed in /etc = K22acct
The file listed in /etc = K28.lms
The file listed in /etc = K28.snmpgtw
etc...etc...
------------------------

With the for statement, each item in the list is assigned to the variable named 
in the for statement line. That variable may then be substituted as part of the 
commands of the for statement.


--------------------------------------------
Using the while Statement 
--------------------------------------------

#!/bin/ksh
# filename:  showwhile
#
print "Showing the while Statement in Shell Scripts"

	let CNT=1
	while ((CNT != 3))
	do
		print "The loop count = $CNT"
		let CNT=CNT+1
	done

let CNT=1

while :
do
	print "This is an endless loop. Count = $CNT"
	let CNT=CNT+1

	if (( CNT == 10 )); then
		break
	fi
done
---------------------------------------------------

-->showwhile
Showing the while Statement 
The loop count = 1
The loop count = 2
This is an endless loop. Count = 1
This is an endless loop. Count = 2
This is an endless loop. Count = 3
This is an endless loop. Count = 4
This is an endless loop. Count = 5
This is an endless loop. Count = 6
This is an endless loop. Count = 7
This is an endless loop. Count = 8
This is an endless loop. Count = 9
---------------------------------------

-------------------------
Using the case Statement 
-------------------------

#!/bin/ksh
# filename: showcase
#
print "Showing the case Statement"

if [[ $# -lt 1 ]]; then
	print "You Must Enter At Least One Argument"
	exit 1
fi

for args in "$@"
do
	case $args in

		1) print "The argument must have been a 1";;
		2) print "The argument must \c";
		   print "have been a 2";;
		3) cat showcase;;
		*) print "I didn't understand the argument: $args";;

	esac
done

-------------------------------------------------
-->showcase 1 2 6 9 p t3st
Showing the case Statement in Shell Scripts
The argument must have been a 1
The argument must have been a 2
I didn't understand the argument: 6
I didn't understand the argument: 9
I didn't understand the argument: p
I didn't understand the argument: t3st
-------------------------------------------------

In a case statement, the '*' character is used as a default operation. 
If it is used, it should be the last entry in the case statement list.


--------------------------
Using the until Statement 
--------------------------

#!/bin/ksh
# filename:  showuntil
print "Showing the until Statement"

let CNT=5

until (( CNT == 0 ))
do
	print "The loop count = $CNT"
	(( CNT = CNT ^^ 1 )) #instead of let CNT=CNT-1 ^^ allows
					#whitespace in the arguments
	sleep 1
done
print "BANG"
--------------------------------------------
--> showuntil
Showing the until Statement in Shell Scripts
The loop count = 5
The loop count = 4
The loop count = 3
The loop count = 2
The loop count = 1
BANG

------------------------------------------------

The while conditional statement will EXECUTE the commands while the given condition is TRUE. 
The until conditional statement will EXECUTE the commands until the given condition is FALSE.


----------------------------------
Conditional Statements Summary
----------------------------------

The test and [  ] statements have been replaced by [[  ]].  

-------------------------------------------
The conditional statement has these formats:

if [ condition ]
if test condition
	if [[ condition ]]
	if (( integer condition ))

There are a large number of arguments available for use 
within the conditional statement. For example:

-r file ..... True if the file exists and is readable
-w file ..... True if the file exists and is writeable
-x file ..... True if the file exists and is executable
-f file ..... True if the file exists and is an ordinary file
-d file ..... True if the file exists and is a directory
-s file ..... True if the file exists and size is > zero.

The following are for string [[  ]] tests:
n1 -eq n2 ... True if number n1 equals n2
n1 -ne n2 ... True if number n1 not equal to n2
n1 -gt n2 ... True if number n1 greater than n2
n1 -ge n2 ... True if number n1 greater than or equal to n2
n1 -lt n2 ... True if number n1 less than n2
n1 -le n2 ... True if number n1 less than or equal to n2
-n str ...... True if str is not null (length > 0)
-z str ...... True if str is null (length == 0)

The following are for integer ((  )) tests:
n1 == n2 ... True if number n1 equals n2
n1 != n2 ... True if number n1 not equal to n2
n1 > n2 .... True if number n1 greater than n2
n1 >= n2 ... True if number n1 greater than or equal to n2
n1 < n2 .... True if number n1 less than n2
n1 <= n2 ... True if number n1 less than or equal to n2
n1 && n2 ... True if number n1 AND n2
n1 || n2 ... True if number n1 OR n2

!  .......... Logical Negation Operator
&& .......... Logical AND Operator
|| .......... Logical OR Operator
-------------------------------------------------------------------------
NOTE: The Logical AND Operator has higher precedence 
than the OR Operator unless the condition is enclosed in parentheses.
-------------------------------------------------------------------------
All operators and flags must be separated by spaces on  the 
command line, as they are separate arguments to the command test. 
-------------------------------------------------------------------------

A variable which can be a null string, must be surrounded with double 
quotes ("..."), when compared, to separate it from 'no string at all'. 
e.g. The command test -s "$A" is always correct. 
The command -s $A will generate a syntax error message if $A is the null string, 
unless it is in the [[  ]] test brackets.

if [ -s $file ]        if [ -s "$file" ]

If $file is null the command to test appears as ...

if [ -s ]              if [ -s "" ]

The second form can be interpreted as a null string, while
the first is incorrect syntax, and always evaluates to what you don't want (true).

It is important to note that strings use the '=' or '!=' characters as part of the test. 
While numbers use the characters, -eq, -lt, etc. as part of the test, unless you are 
in integer context, ((  )), as noted in the above tables.


-------------------------
Using test Conditions 
-------------------------

#!/bin/ksh
# filename: showtest

VER="Version 1.0"

#here's two ways of checking, string and integer:

if (( $# < 1 )); then
	print "You must enter at least one argument\n"
	exit 1
fi

#OR
#
#if [[ $# -lt 1 ]]; then
#	print "You must enter at least one argument\n"
#	exit 1
#fi

if [[ $1 = -v || $1 = -V ]]; then
	print $VER
	exit 0
fi

print "Showing test Conditions in Shell Scripts"

if [[ -s $1 && ! -d $1 ]]; then
	print "The file $1 exists and is greater than zero"
elif [[ -d $1 ]]; then
	print "The directory $1 exists"
else
	print "The file or directory $1 does not exist"
fi
-------------------------------------------------
-->showtest
You must enter at least one argument

-->showtest -v
Version 1.0

-->showtest -V
Version 1.0

-->showtest /usr/bin/who
Showing test Conditions in Shell Scripts
The file /usr/bin/who exists and is greater than zero

-->showtest /bin
Showing test Conditions in Shell Scripts
The directory /bin exists

-->showtest bird
Showing test Conditions in Shell Scripts
The file or directory bird does not exist

$showtest v
Showing test Conditions in Shell Scripts
The file or directory v does not exist
---------------------------------------------------

The first if statement tests the number of positional parameter entered. 
If the number is less than 1, meaning that no arguments were entered, 
then the script informs the operator of the error and exits.

The second if statement tests for the string values of '-v' and 
'-V'. If the entry matches one of these strings, the version number 
of the show_test script is displayed.

The third if statement tests to see if the file ($1) exists AND is 
not a directory. You have to remember that directories in the system are also 
files. Therefore, without the second test condition the script would have 
determined that directories are files, displayed that the file exists and is 
greater than zero and completed the script.

The fourth if statement is used to test for the argument being a directory if 
it is not a regular file. If the argument is a directory then it indicates this. 
If the argument is not a file or directory then it indicates that it is neither 
a file or directory and completes.

---------------------------------------
Using a read Statement for User Input
---------------------------------------

#!/bin/ksh
#  filename: showread
VER="Version 1.0"

if [[ $1 = '-v' || $1 = '-V' ]]; then
	print $VER
	exit 0
fi

print "Showing the read Statement in Shell Scripts\n"

while :
do
	print "Enter a file/directory name or 'QUIT' to exit: \c"
	read answer

	if [[ -z $answer ]]; then
		continue
	fi

	if [[ $answer = 'quit' || $answer = 'QUIT' ]]; then
		break
	fi

	if [[ -f $answer ]]; then
		print "$answer is a regular file in the system"
	elif [[ -d $answer ]]; then
		print "$answer is a directory in the system"
	else
		print "$answer is not a file or directory in the system"
	fi
done

--------------------------------------------------------

-->showread
Showing the read Statement in Shell Scripts

Enter a file/directory name or 'QUIT' to exit: /bin/ls
/bin/ls is a regular file in the system
Enter a file/directory name or 'QUIT' to exit: /bin/ksh
/bin/ksh is a regular file in the system
Enter a file/directory name or 'QUIT' to exit: /foobar
/foobar is not a file or directory in the system
Enter a file/directory name or 'QUIT' to exit: /home/test
/home/test is a directory in the system
Enter a file/directory name or 'QUIT' to exit: QUIT

---------------------------------------------------------------

#!/bin/ksh
# Example script: Used for formatting a number of floppy disks
# performs a loop to format a number of diskettes. Note the 
# regular expression in the while test condition ^^ it matches
# either y or Y

ANSWER='y'

while [[ $ANSWER = @(y|Y) ]]
do 
	print "Formatting - please be patient\n"
	format /dev/mf0
	if [ $? -ne 0 ]; then 
		print "Problem with disk \n"
		print "Insert another disk and press y to continue\n"
		print "Or press other key to exit"
		read ANSWER
		continue
	else
	print "Do you wish to format another y/n?\n"
		read ANSWER
		continue
	fi
done

-----------------------------------------------------

#!/bin/ksh
# filename: select

#############################################################
#
#  This shows how to use the select option of the KORN Shell
#
#############################################################

print "\n"  #Just for readability

PS3=$(print "\nPlease enter a number: ") #Wanted the newline

select cmd in date pwd ls quit
do
  case $cmd in
    date | pwd | ls) print  \
                     "\nYou selected: $REPLY which was: $cmd";;

    quit) print "\nYou selected: $REPLY which was: $cmd\n";
          break;;

    *) print "\nYour selection was out of range\n";;

    esac

done

------------------------------------------------------------

Arrays are one dimensional and are of the format 
variable[subscript]. The subscript must evaluate to a number in the range of 0-1023.


------------
Using Arrays 
------------


#!/bin/ksh
# filename: arrays

integer CNT=0  # Arrays start with zero and declare cnt being 
               # an integer

for data in This is a test of this beast
do

	text[CNT]=$data
	CNT=CNT+1  #let and $CNT not required for integer values
done

integer DISP=0  #Display Value
until [[ $CNT < 0 ]]
do

	print "The data stored was: ${text[DISP]}"
	CNT=CNT-1
	(( DISP = DISP + 1 ))  #need ((  )) for spaces in expr
done

# Show what happens when you reference an array without 
#     subscript 
print "\nThe first data stored was: ${text}\n"

# The characters * and @ can be used to access all data #
print "Data Stored: ${text[*]}\n"

# Show difference of * and @ when inside of quotes #
for data in "${text[*]}"
do
	print "[*]: $data\n"
done

for data in "${text[@]}"
do
	print "[@]: $data"
done

------------------------------------------------
The KORN shell provides an elif command as part of an if 
statement that is similar to the elseif statement in other languages.  
It is a short cut to doing an else statement followed by an if statement.  

Similar to the if statements, a then must follow for the elif statements.  

Remember, if you are testing one argument for a number of values, 
it is better to do a case statement rather than a series of if statements. 

-----------------------
Using the elif Command
-----------------------
#!/bin/ksh
PS3=$(print "\nPlease enter a number: ") #Wanted the newline

select cmd in date pwd ls quit
do
	if [[ $cmd = date ]]; then
		print "You selected: $REPLY which was: date\n"
	elif [[ $cmd = pwd ]]; then
		print "You selected: $REPLY which was: pwd\n"
	elif [[ $cmd = ls ]]; then
		print "You selected: $REPLY which was: ls\n"
	elif [[ $cmd = quit ]]; then
		print "You selected: $REPLY which was: quit\n"
		break
	else
		print "Your selection was out of range\n"
	fi
done
--------------------------------------------------


ebook:
Full Size
Jeep Buyer's
Guide
ebook:
Practical Suggestions
for Microsoft
Windows
Linux Tackles Microsoft
12 hour Video Course by john:
The Art of Linux System Administration
published by O'Reilly Media
Study Guide for the LPIC-2 Certification Exams
search for:
on the internet, or:
JohnMeister.com-fotos
LinuxMeister-Linux
BibleTech-
Bible overview


An overview of Biblical history:
"Promises and Prophets"

Wagoneers

FULL SIZE JEEPS

JeepMeister
"Jeep is America's
only real sports car."
-Enzo Ferrari


MeisterTech
Diesels +

One Page Overview of Linux Commands

click for an image of the 5 essential Linux commands

An Intro to Linux
AMSOIL product guide,
or, AMSOIL web, or 1-800-956-5695,
use customer #283461

Amsoil dealer since 1983
purchase AMSOIL
at Midway Auto on SR9 in Snohomish,
or at Northland Diesel in Bellingham, WA


SJ - 1962-1991

XJ - 1984-2001

WJ - 1999-2004

KJ - 2002-2007

WK - 2005-2010

Find the recommended
AMSOIL synthetics
for your Jeep

CJ-10A - 1984-1986

Jeepsters

MJ - 1984-1992

Willys - 1946-1965

Other Jeeps (FC)