I've been looking for standards on "correct" variable scope in ksh but the IEEE Std 1003.1-2008 stuff on the Open Group site doesn't mention any rules? http://www.opengroup.org/onlinepubs/9699919799/utilities/contents.html
I found an interesting behavior in our ksh (pdksh) implementation, and I'd like to know if the behavior is considered correct? When you append to a variable within a 'for' loop, the changes are exist after the loop ends, but if you do the same within a 'while' loop, the changes are lost? Example Code: ******************************************************************** #!/bin/ksh # Test Setup mkdir testdir cd testdir touch f00.txt f01.txt f02.txt ls -1 f0?.txt >list.txt # $ cat flist.txt # f00.txt # f01.txt # f02.txt # Set the Internal Field Separator to newline. IFS=' '; # Append space separated list elements to a variable inside a for loop. printf "\n\nTesting 'for' Loop\n"; for FNAME in `cat list.txt`; do if [[ -z $FLIST ]]; then FLIST="$FNAME"; else FLIST="$FLIST $FNAME"; fi; printf "FLIST: %s\n" "$FLIST"; done; # Reset the Internal Field Separator to space (default). IFS=' '; # Print out all list elements in the variable. printf "\n*** List From 'for' Loop ***\n"; for FNAME in $FLIST; do printf "FILE_LIST_ELEMENT: %s\n" "$FNAME"; done; printf "\n\nTesting 'while' Loop\n"; # Now we try the same type of thing with the 'while' loop. cat list.txt | while read -r WNAME; do if [[ -z $WLIST ]]; then WLIST="$WNAME"; else WLIST="$WLIST $WNAME"; fi printf "WLIST: %s\n" "$WLIST"; done # Print out all list elements in the variable. printf "\n*** List From 'while' Loop ***\n"; for WNAME in $WLIST; do printf "FILE_LIST_ELEMENT: %s\n" "$WNAME"; done exit 0 ******************************************************************** With both the 'for' and the 'while' loops, when the loop is running the changes made to the variable are available, but once you leave the scope of the loop (do,done), the behavior of variables modified within the two types of loops differ. I realize the IEEE/POSIX standard was based on ksh93, and our pdksh is only partially compliant with ksh93, but I'm wondering if the "correct" behavior for variable scope is formally standardized and/or documented anywhere? -- J.C. Roberts