LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   script read input from file (https://www.linuxquestions.org/questions/linux-newbie-8/script-read-input-from-file-4175459526/)

slowerogue 04-25-2013 03:02 AM

script read input from file
 
hi guys
i want the variable GN has the input from file
Code:

GN="/tmp/scripts/groupname"
jailpath="/data/$GN"

cat ${GN} | \
while read GN2
do
  GN=${GN2}
  echo $GN
done


echo $GN


the echo $GN does show what i want, but only before the "done"
when i echo $GN outside the while-do thing, it goes back to original,means my jailpath cannot get the correct value

any helps on how to solve this? ><
thanks

chrism01 04-25-2013 03:50 AM

Try reading the file from the bottom of the loop http://stackoverflow.com/questions/8...e-line-by-line.
Your one opens a new shell (& env) due to the pipe.

shivaa 04-25-2013 05:03 AM

As Chris said, try this:
Code:

#!/bin/bash
GN="/tmp/scripts/groupname"
jailpath="/data/$GN"

while read -r GN2
do
  GN=${GN2}
  echo $GN
done < ${GN}

echo $GN


David the H. 04-25-2013 02:30 PM

Another description for you:

I set variables in a loop that's in a pipeline. Why do they disappear after the loop terminates? Or, why can't I pipe data to read?

http://mywiki.wooledge.org/BashFAQ/024

Using a redirection for the file input also avoids a Useless Use Of Cat.


And please lose the pointless curly brackets around the variables, ok? They do nothing but clutter up the code. Save the full variable form for when you really need it.

slowerogue 04-25-2013 11:26 PM

thanks guys, it worked


All times are GMT -5. The time now is 05:02 PM.