Find the answer to your Linux question:
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.
  1. #1
    Just 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

  2. #2
    Linux 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.

    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
    This method doesn't spawn a child process.

  3. #3
    Just 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?

  4. #4
    Linux 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.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •