0
$ c=$(./getnumbers -n 5)
$ echo $c
1 2 3 4 5
$ ./getnumbers -n 5
1
2
3
4
5

How do I get it to store inside the variable as a column and not a row?

  • `echo $c` does *not* show what's in the variable. The lack of quotes [may interfere](https://unix.stackexchange.com/a/131767/108618), this apparently happens here. `echo "$c"` is better, `printf '%s\n' "$c"` [even better](https://unix.stackexchange.com/q/65803/108618). In general a variable may include characters or sequences that make the terminal do something (rather than print something), so you need `printf '%s' "$c" | od -c` or similar command to *really* tell what's in the variable; or (in Bash) `declare -p c`. – Kamil Maciorowski Oct 02 '22 at 21:35
  • Does this answer your question? [Why does my shell script choke on whitespace or other special characters?](https://unix.stackexchange.com/questions/131766/why-does-my-shell-script-choke-on-whitespace-or-other-special-characters) – Kamil Maciorowski Oct 02 '22 at 21:35
  • Does this answer your question? [Why do newline characters get lost when using command substitution?](https://unix.stackexchange.com/questions/164508/why-do-newline-characters-get-lost-when-using-command-substitution) – G-Man Says 'Reinstate Monica' Oct 03 '22 at 08:49

1 Answers1

1

The output is stored "as a column", i.e. with the \n between lines preserved:

$ c=$(./getnumbers -n 5)
$ echo $c
1 2 3 4 5
$ echo "$c"
1
2
3
4
5

Without the " quotes, what is happening is that the shell is passing the output lines to echo as individual arguments. echo in turn then does its job and outputs them all - with only a space between them. With the " quotes, $c is passed to echo without being interpreted by the shell, so echo is then able to output the value correctly, as it was captured.

Andre Beaud
  • 406
  • 1
  • 6