Find the answer to your Linux question:
Results 1 to 4 of 4
Hi there, I've got a problem writing a piece of shell script. Here is the simplified code : Code: #!/bin/sh tmp="value_I_dont_care" cat $1 | while read line do tmp="value_I_care" done ...
Enjoy an ad free experience by logging in. Not a member yet? Register.
  1. #1
    Just Joined!
    Join Date
    Jun 2005
    Location
    Belgium
    Posts
    3

    Bash script - Help on retrieving variable from inside a loop


    Hi there,

    I've got a problem writing a piece of shell script.
    Here is the simplified code :

    Code:
    #!/bin/sh
    
    tmp="value_I_dont_care"
    
    cat $1 |
    while read line 
    do
    	tmp="value_I_care"
    done
    
    echo $tmp
    When I run the script, it writes "value_I_dont_care", but i'd want it to show me "value_I_care" (of course in the full script I use $line, uh )

    Is there a way to define variables to global or something like this?
    I haven't found anything on the few tutorials I've read.

    Thanks in advance for any help

    Simon

  2. #2
    Linux Guru anomie's Avatar
    Join Date
    Mar 2005
    Location
    Texas
    Posts
    1,692
    If you are asking how to define variables globally, you can use export.

    Code:
    export VAR1=value
    or

    Code:
    VAR1=value
    export $VAR1

  3. #3
    Just Joined!
    Join Date
    Jun 2005
    Location
    Belgium
    Posts
    3
    Thanks for the answer, but that small piece of... code () still writes "value_I_dont_care" with the last echo

    Can this come from my
    Code:
    cat $1 |
    ?

  4. $spacer_open
    $spacer_close
  5. #4
    Just Joined!
    Join Date
    Jun 2005
    Location
    Belgium
    Posts
    3
    Alright, I just resolved my problem.
    the bug was coming from the
    Code:
    cat $1 |
    indeed...

    So, if you have the same problem, just write it like this instead :


    Code:
    #!/bin/sh 
    
    tmp="value_I_dont_care" 
    
    
    while read line 
    do 
       tmp="value_I_care" 
    done < $1
    
    echo $tmp

Posting Permissions

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