I'd like to sort based on the output of a mercurial (hg) command. The output from hg log
is collapsed into 1 line when piping to another command but I want to keep separate lines.
Here's a minimum reproducible case:
# Initial setup
mkdir /tmp/hgbug; cd /tmp/hgbug; hg init;
touch README.md; hg add README.md
h commit -m "initial commit"
# Bug - the echo command replaces a complex find command
echo '1a\n2b\n3c\n' | xargs -I % hg log --template '%' | sort
# Actual Output
# 1a2b3c
# Expected Output
# 1a
# 2b
# 3c
The interesting part is that mercurial doesn't collapse the lines when the output isn't piped or redirected.
echo '1a\n2b\n3c\n' | xargs -I % hg log --template '%'
# Actual Output
# 1a
# 2b
# 3c
How do I prevent mercurial from collapsing lines when redirecting output?
To clarify, here's a more complete example comparing the output of hg
with echo
using both xargs
and a while
loop.
#!/bin/bash
cd /tmp/hgbug
echo '# hg log - xargs'
echo $'1a\n2b\n3c' | xargs -I {} hg log --template "hg-{}" | sort
echo
echo '# plain echo - xargs'
echo $'1a\n2b\n3c' | xargs -I {} echo "echo-{}" | sort
echo
echo '# hg log - while read'
echo $'1a\n2b\n3c' | while read -r file; do hg log --template "hg-$file"; done | sort
echo
echo '# plain echo - while read'
echo $'1a\n2b\n3c' | while read -r file; do echo "echo-$file"; done | sort
That script outputs the following:
# hg log - xargs
hg-1ahg-2bhg-3c
# plain echo - xargs
echo-1a
echo-2b
echo-3c
# hg log - while read
hg-1ahg-2bhg-3c
# plain echo - while read
echo-1a
echo-2b
echo-3c
xargs
sets a parameter for each line extracted from the input. It is up to the target program to decide how to handle multiple parameters. If you need one parameter at a time, don't usexargs
; instead, usefind ... -exec hg log --template {} \;
orfind ... | while read -r file; do hg log --template "$file"; done
(note my use and omission of quotes).GNU xargs
with the-I
param implies-L 1
, or one line per invocation. So, there's 3hg log
invocations. I'd like to stick withxargs
to use the parallelism feature. If I use echo instead of hg, everything works as expected.hg
toecho
to help illustrate the problem.hg log
doesn't add trailing newlines when output is redirected. The behavior makes sense, but is surprising when trying to figure out the differences between interactive and redirected output.