In general, echo "$(foo)"
is silly and pretty much equivalent to just foo
. The difference there is that the command substitution removes all trailing newlines from output of foo
, and echo
adds exactly one (and might process backslashes, but let's assume it doesn't). Usually, that doesn't change anything, since the output is likely to have exactly one in the end.
But if the output of foo
is missing the final newline, it does mean that the combination of echo
and command substitution fixes that, making sure that the right-hand side of the pipe gets a proper text file as input. That's important in principle, since technically the POSIX standard requires that the inputs must be proper text files, apparently leaving open the possibility of unexpected behaviour if they aren't.
In practice, I've never seen an implementations of grep
that croaked on such a technically invalid input, or treated the final newline-less line fragment any differently than other lines. Considering how grep works, essentially ignoring the newlines, it's not obvious how misbehavior on that could easily happen. (Also, fgets()
, the C standard function for reading a line also doesn't really care if there is a newline at the end or not, unlike e.g. the shell's read
, where the exit status depends on if a newline was seen or not. Then again, if the utility doesn't check what it read, assumes there must be a newline at the end, and removes the final character unconditionally, with something like buf[strlen(buf) - 1] = '\0'
, then that would eat the final regular character if the final newline was missing.)
That said, I also don't believe that's actually the reason they went for that odd-looking command. (And I don't think systemctl
produces improper output.) It's morely likely that they just weren't really thinking what they were doing.
systemctl
's stdout connected to a pipe (or a socket), which should disable any auto-pagination if it works sensibly. Most of the time what matters is if the stdout is connected to a terminal. – ilkkachu Jan 06 '24 at 09:54systemctl
sees, but I doubt there is one. – ilkkachu Jan 06 '24 at 15:40ispipe() { perl -e 'printf STDERR "STDOUT is a pipe: %s\n", (-p STDOUT ? "yes" : "no")'; }
; I get a positive answer for bothispipe |cat
anda=$(ispipe)
in Bash. (But in the ksh I have, the pipe is done using a socket, and the command substitution with a file...) – ilkkachu Jan 06 '24 at 15:46