1

The bash version in my system’s running version of Debian is:

bash --version|awk 'NR==1'
GNU bash, version 5.1.4(1)-release (x86_64-pc-linux-gnu)

In Eyal Levin's answer on this other Stack Overflow thread it recommends this:

Example:

$ echo "title\nvalue1\nvalue2\nvalue3" | (read line; echo "$line"; grep value2)

Output:

title
value2

In my Bash console I run this:

debian@debian:~$ echo "title\nvalue1\nvalue2\nvalue3" | (read line; echo "$line"; grep value2)
titlenvalue1nvalue2nvalue3
debian@debian:~$ 

Why the command output different result in my OS?

echo "title\nvalue1\nvalue2\nvalue3" | (read line; echo "$line"; grep value2)
Giacomo1968
  • 53,069
  • 19
  • 162
  • 212
showkey
  • 89
  • 4
  • 16
  • 40

1 Answers1

2

For some reason, echo behaves differently on different platforms.

So, as this Stack Overflow answer explains, replace echo with printf for consistent output across different platforms.

Knowing that, change your command to use printf like this:

printf "title\nvalue1\nvalue2\nvalue3" | (read line; echo "$line"; grep value2)

Or you could just add the -e parameter to echo to “enable interpretation of backslash escapes” as the echo man page explains.

echo -e "title\nvalue1\nvalue2\nvalue3" | (read line; echo "$line"; grep value2)

Tested this and it works on Bash on Ubuntu 20.04:

GNU bash, version 5.0.17(1)-release (x86_64-pc-linux-gnu)

And it also works as well on the weirdo version of Bash that macOS Monterey (12.6) Apple has cooked up:

GNU bash, version 3.2.57(1)-release (x86_64-apple-darwin21)
Giacomo1968
  • 53,069
  • 19
  • 162
  • 212
  • 1
    Don't use `echo -e`; some versions will print "-e" as part of the output. It is simply not possible to count on the output from `echo` if you pass it any options or there are backslashes in the string (see [this Unix & Linux answer for more info](https://unix.stackexchange.com/questions/65803/why-is-printf-better-than-echo/65819#65819)). If you want reliable results, use `printf` instead. – Gordon Davisson Oct 17 '22 at 10:03
  • @GordonDavisson Thus why I mentioned `printf` first. – Giacomo1968 Oct 19 '22 at 20:45