0

I have two scripts:

  1. in bash

    #!/bin/bash
    H_VARIABLE=empty
    echo "Zeile1
          Zeile2" |
    while read satz
     do 
      H_VARIABLE="$H_VARIABLE $satz"
    done
    echo H_VARIABLE=$H_VARIABLE
    

    Result:

    H_VARIABLE=empty
    
  2. in ksh

    #!/usr/bin/ksh
    H_VARIABLE=leer
    echo "Zeile1
          Zeile2" |
    while read satz
     do
      H_VARIABLE="$H_VARIABLE $satz"
    done
    echo H_VARIABLE=$H_VARIABLE
    

    Result:

    H_VARIABLE=leer Zeile1 Zeile2  
    

Conclusion: leer Zeile1 Zeile2 != leer

What can I do in bash to get the same response as in ksh?

muru
  • 193,181
  • 53
  • 473
  • 722
  • 1
    In addition to steeldriver's answer which is correct, you might want to have a look at bash debugging tools like `shellcheck` you can find its homepage [here](http://www.shellcheck.net/). Cheers – Videonauth May 12 '16 at 15:43

1 Answers1

2

The issue here is that, in bash, the while loop gets executed in a subshell when it is on the RHS of a pipe. You could do instead

H_VARIABLE=leer
while read satz
  do H_VARIABLE="$H_VARIABLE $satz"
done < <(
echo "Zeile1
      Zeile2"
)

using process substitution or, using a here string

H_VARIABLE=leer
while read satz
  do H_VARIABLE="$H_VARIABLE $satz"
done <<< "Zeile1
          Zeile2"

See also bash script var not changed after the loop

steeldriver
  • 131,985
  • 21
  • 239
  • 326