0

I have a problem with one of my bash scripts. I have a variable and a function defined, something super simple:

RESULT='{"single":[],"theme":[],"imagesheet":[]}'

addResult() {
    type=$1
    filename=$2

    OP=".${type} += [\"${filename}\"]"
    RESULT=$(echo $RESULT | jq "$OP")
}

I call this addResult function and check the $RESULT variable and I can see that it is changed, and the json grows.

However, I also call this function from a loop:

grep -Rh "\.Image(\"" $MY_DIR | while read LINE; do

    addResult single "${LINE}"

done

When I check the variable from inside the loop, I can see that the entries are added to the json. However, immediately after the loop ends, the $RESULT variable loses all of the entries that were added inside the loop. What can I do, to make the changes made inside the loop remain?

EDIT: Thanks to @marcolz I have modified my call to:

RESULT=$(grep -Rh "\.Image(\"" $MY_DIR | while read LINE; do check_imagesheets $LINE; done; echo $RESULT)

Unfortunately, the check_imagesheets function is quite large and it also contains quite some echo calls which pollute the final echo $RESULT. What other approach could I take to mitigate this issue?

Krystian
  • 3,193
  • 2
  • 33
  • 71
  • As the variable is only set in the subshell that handles the commands after the pipe (`|`), either use the variable in that subshell, or pass the result afterwards. – marcolz Feb 06 '18 at 09:29
  • @marcolz could you give me a tip on how can I do that? – Krystian Feb 06 '18 at 09:34
  • for instance like: `OUTER_RES="$(grep -Rh "\.Image(\"" $MY_DIR | { while read LINE; do addResult single "${LINE}";done; echo $RESULT; } )"` – marcolz Feb 06 '18 at 09:39
  • yeah, that's the problem. The code I pasted is an excerpt of what's going on in the loop. The whole body was far larger. I have moved the body into a function, cool, but inside there are plenty of echo's which I can't remove. This pollutes the last one and I end up with incorrect value. – Krystian Feb 06 '18 at 09:56
  • 1
    `while read LINE; do addResult single "${LINE}"; done < <(grep -Rh '\.Image("' $MY_DIR)` You lose anything in the pipe when it's closed, i.e the copy of `RESULTS` that you're appending to. – 123 Feb 06 '18 at 10:21
  • thanks a lot guys. I have used what @123 proposed. – Krystian Feb 06 '18 at 10:31

1 Answers1

1

An answer in the linked possible duplicate points to: the Bash FAQ

In your case you could use a named pipe or shopt -s lastpipe might work for you.

marcolz
  • 2,880
  • 2
  • 23
  • 28