theta
theta

Reputation: 25601

Make use of variable from while read loop

In my bash script I use while read loop and a helper function fv():

fv() {
    case "$1" in
    out) echo $VAR
    ;;
    *  ) VAR="$VAR $1"
    ;; 
    esac
}

cat "$1" | while read line
    do
        ...some processings...
        fv some-str-value
    done

echo "`fv out`"

in a hope that I can distil value from while read loop in a variable accessible in rest of the script. But above snippet is no good, as I get no output.

Is there easy way to solve this - output string from this loop in a variable that would be accessible in rest of the script - without reformatting my script?

Upvotes: 3

Views: 7214

Answers (3)

Kevin
Kevin

Reputation: 56049

As no one has explained to you why your code didn't work, I will.

When you use cat "$1" |, you are making that loop execute in a subshell. The VAR variable used in that subshell starts as a copy of VAR from the main script, and any changes to it are limited to that copy (the subshell's scope), they don't affect the script's original VAR. By removing the useless use of cat, you remove the pipeline and so the loop is executed in the main shell, so it can (and does) alter the correct copy of VAR.

Upvotes: 5

sgibb
sgibb

Reputation: 25726

Replace your while loop by while read line ; do ... ; done < $1:

#!/bin/bash

function fv
{
    case "$1" in
    out) echo $VAR
    ;;
    *  ) VAR="$VAR $1"
    ;; 
    esac
}

while read line
    do
        fv "$line\n"
    done < "$1"

echo "$(fv out)"

Upvotes: 4

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798456

Stop piping to read.

done < "$1"

Upvotes: 1

Related Questions