Home > Software engineering >  Variables stored in subshell
Variables stored in subshell

Time:04-14

The script is reading the text from the .csv file and storing it as variables in subshell I believe, after that I want to use those variables in shell but they are blank, how to modify the script so it will always remember those variables?

INPUT=file.csv
IFS=','
while read line1
do
echo "this is $line1"
done < $INPUT

echo "test $line1"

CodePudding user response:

The while in your script is not working in subshell. The variable line1 will be empty just after exiting the loop because read encounters end of file, which is the condition to exit the loop. The variable line1 is overwritten to empty string at that moment. Please try the following script:

INPUT=file.csv
IFS=','
while read -r line1
do
    echo "this is $line1"
    break
done < "$INPUT"

echo "test $line1"

Then you'll see the variable $line1 holds the value of the 1st line in the input file. If you want to preserve the value of $line1, assign another variable to it in the loop:

INPUT=file.csv
IFS=','
while read -r line1
do
    echo "this is $line1"
    line=$line1
done < $INPUT

echo "test1 $line1"
echo "test2 $line"

BTW the IFS will not work to split the line because you are putting just one variable. If you want to split the line into multiple variables, please try:

while IFS=, read -r col1 col2 ..

or

while IFS=, read -r -a ary

depending on the purpose.

  •  Tags:  
  • bash
  • Related