0

Can someone help me to store multiline output in variable in bash. I have the following code:

# FILES[1] contents:
# age people.csv
# ...data...

FILE="${FILES[1]}"

cmd=$(head -n 1 "$FILE")
cmd="./corona $cmd"
echo "Command to run: ${cmd[*]}"
output=$(eval "$cmd")
echo "$output"

I'm trying to store the output of corona script in output variable. But it doesn't seem to work. The output stucks at

Command to run: ./corona age people.csv

And on the second line I can see only the blinking cursor. But when I press Ctrl+D it suddenly prints all the output from corona script and stops. So, probably, the echo command works just after pressing the shortcut.

Also, I'd like to mention, that variable FILES is an array of filenames. So the FILE variable is a name of the file. It has command arguments to run on the first line and other data starting from the second line.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • 1
    `${cmd[*]}` does not make sense when `$cmd` is not an array. – John Bollinger Mar 29 '22 at 21:36
  • 1
    As for the script waiting for a Ctrl-D, that sounds like `./corona` is attempting to read from its standard input. If you don't intend to present any input that way then you should probably redirect the standard input of the command to be from `/dev/null`. – John Bollinger Mar 29 '22 at 21:41
  • If you want an actual answer, then we need to know at least something about what `./corona` is and does. – John Bollinger Mar 29 '22 at 21:45
  • 1
    When you run `./corona age people.csv` manually in the terminal, does it complete without needing to type Ctrl-D ? – Philippe Mar 29 '22 at 22:03
  • Likely dupe of [How can I have a newline in a string in sh?](https://stackoverflow.com/q/3005963/3422102), or [Trying to embed newline in a variable in Bash](https://stackoverflow.com/questions/9139401/trying-to-embed-newline-in-a-variable-in-bash) – David C. Rankin Mar 30 '22 at 07:18

1 Answers1

0

Here is a sample script I developed to read the output of ls into a variable. You could use the same technique.

#!/bin/bash

my_array=()
while IFS= read -r line; do
    my_array+=( "$line" )
done < <( ls )
echo ${#my_array[@]}
printf '%s\n' "${my_array[@]}"