0

The following is the sample while loop.

res=()
lines=$'first\nsecond\nthird'
while read line; do
res+=("$line")
done <<< "$lines"
echo $res

When i run this directly in terminal im getting the following out put.

first second third

But when run the same script by saving it to a file. Then im getting the following out put.

first

Why is it behaving differently?

Note: I tested with and without shebang in file. result is same.

lokanadham100
  • 1,149
  • 1
  • 11
  • 22
  • 2
    Use `echo "${res[@]}"` to print all array elements – anubhava Nov 20 '20 at 16:36
  • 2
    Look at the output of `declare -p lines`; in the case where you see all three entries, it's actually a single element containing linebreaks (which are removed by the unquoted parameter expansion). – Benjamin W. Nov 20 '20 at 16:43
  • [ShellCheck](https://www.shellcheck.net) automatically detects [this](https://github.com/koalaman/shellcheck/wiki/SC2128) and other common problems – that other guy Nov 20 '20 at 16:54
  • 1
    I'm guessing when you run it "directly" your shell is not bash but zsh. Only printing `first` is correct/expected/normal behavior when you have `res=( first second third )` and then run `echo $res`; you would need to use `"${res[@]}"` to expand all three elements. – Charles Duffy Nov 20 '20 at 16:55
  • @CharlesDuffy, yes, i forgot the fact that it is zsh. Thanks!!!. – lokanadham100 Nov 21 '20 at 13:51

1 Answers1

0

If you have a string with embedded newlines and want to turn it into an array split on them, use the mapfile builtin:

$ mapfile -t res <<<$'first\nsecond\nthird'
$ printf "%s\n" "${res[@]}"
first
second
third
Shawn
  • 47,241
  • 3
  • 26
  • 60