bashripgrep

Behaviour of Bash command changes in $()


When running Ripgrep normally in Bash, the output is formatted as follows:

$ rg asdfghjkl
my_file
1:asdfghjkl

But if I attempt to capture the output with $(), the format is different:

$ foo=$(rg asdfghjkl)
$ echo "$foo"
my_file:asdfghjkl

What causes this disparity? Is Ripgrep changing its behaviour, or does $() not really capture stdout?

My best guess is that Ripgrep is the issue rather than Bash, though I've not been able to find anything documenting this behaviour.


Solution

  • It is ripgrep. You can see the same behavior by other commands. E.g ls prints entries in columns ls | cat prints them one per line. grep something will usually colorize the match but with grep | cat the color is gone.

    Commands can and do test if the standard output is connected to an interactive terminal (your first example) or not (your second example which is basically the same as a pipeline).

    Same exist for standard input where a command could check if it is connected to a terminal to decide if it should show a password prompt or not.

    Usually the output a command produces for the pipeline case is more suitable for parsing and using in scripts. And you might check if ripgrep has options to force a specific output format.