Results 1 to 4 of 4
I have a sh script that loops through a file and sets a variable. After coming out of the loop the variable is no longer set. Below is the code ...
Enjoy an ad free experience by logging in. Not a member yet? Register.
- 06-02-2009 #1Just Joined!
- Join Date
- Jun 2009
- Posts
- 2
Variables Not Staying Set
I have a sh script that loops through a file and sets a variable. After coming out of the loop the variable is no longer set. Below is the code snippet:
chk4ASM()
{
cat /etc/oratab | while read line
do
ASMHM=`echo ${line} | grep -i "^+asm"| cut -d ":" -f 2`
[[ ! -z ${ASMHM} ]] && echo "ASM home is [ ${ASMHM} ] "
[[ ! -z ${ASMHM} ]] && break
done
echo "ASM home = ${ASMHM}"
if [ -z ${ASMHM} ]
then
echo "Unable to determine ASM home. Please check /etc/aoratab" \
echo "and ensure there is an ASM entry."
exit 1
fi
The variable $ASMHM is not set after coming out of the loop even if the var is exported. This is the case in sh, bash, ksh. Any ideas? This same function sets the var in an AIX environment.
Thanks
-Mike
- 06-03-2009 #2Linux Newbie
- Join Date
- Mar 2009
- Posts
- 228
Common problem that people run into. When you pipe data to a loop the shell spawns a child process for the loop. The variable is set only in the child process. When the loop exits the child process is terminated. Thus the variable is lost.
The thing to do is use redirection instead of a pipe.
This method doesn't spawn a child process.Code:while read line do ASMHM=`echo ${line} | grep -i "^+asm"| cut -d ":" -f 2` [[ ! -z ${ASMHM} ]] && echo "ASM home is [ ${ASMHM} ] " [[ ! -z ${ASMHM} ]] && break done < /etc/oratab
- 06-03-2009 #3Just Joined!
- Join Date
- Jun 2009
- Posts
- 2
Thanks for that information. Greatly appreciated. Do you have any ideas why this does not occur in an AIX environment?
- 06-03-2009 #4Linux Newbie
- Join Date
- Mar 2009
- Posts
- 228
I guess it's how a shell is implemented on a particular OS. I also work on HP's Tru64 and it occurs there in bash. On Tru64 we also use ksh and in that shell it doesn't occur whereas in Linux it does in ksh.
Just one of those minor differences that makes it annoying when you have to write scripts for use on multiple OS'es.


Reply With Quote
