3

How do I suppress or remove a newline at the end of Bash command substitution?

For example, I have

echo "$(python --version) and more text"

how do I get

Python 2.7.10 and more text

and not

Python 2.7.10
 and more text
orome
  • 45,163
  • 57
  • 202
  • 418

2 Answers2

4

bash command substitution syntax already removes trailing newlines. All you need to do is to redirect to stdout:

$ echo "$(python --version) and more text"
Python 2.7.8
 and more text
$ echo "$(python --version 2>&1) and more text"
Python 2.7.8 and more text
glenn jackman
  • 238,783
  • 38
  • 220
  • 352
  • Ah, I see. I wasn't capturing it at all. There's no value returned, but output is generated (to stdout?), right? – orome Nov 03 '15 at 18:49
  • And: `brew install python`. – orome Nov 03 '15 at 18:51
  • Not on a mac. And yes, not capturing: the `$()` only captures stdout, not stderr, unless you explicitly redirect – glenn jackman Nov 03 '15 at 18:54
  • So `python --version` goes to stderr rather than stdout? Any idea why? E.g. `echo "$(python --version 2>&1) in $(which python)"` works because `which python` goes to stdout, right? – orome Nov 03 '15 at 20:42
  • 1
    "Why" is addressed here: http://stackoverflow.com/q/26028416/7552. To test the results of a program: `which python 2>/dev/null` or `which python >/dev/null` and see if one of them has no output. – glenn jackman Nov 03 '15 at 21:14
3

The thing here is that python --version output to stderr, whereas "and more text" to stdout.

So the only thing you have to do is redirect stderr to stdin using 2 >&1:

printf "%s and more text" "$(python --version 2>&1)"

or

$ echo "$(python --version 2>&1) and more text"
Python 2.7.10 and more text

Note that initially I was piping to tr -d '\n' using |&:

echo "$(python --version |& tr -d '\n') and more text"
Community
  • 1
  • 1
fedorqui
  • 275,237
  • 103
  • 548
  • 598
  • I get `-bash: command substitution: line 1: syntax error near unexpected token `&'` and `-bash: command substitution: line 1: `python --version |& tr -d '\n''`. – orome Nov 03 '15 at 16:44
  • @raxacoricofallapatorius what version of bash are you using? See the linked question when it mentions it needs Bash 4+. A workaround is to say `python --version 2>&1 | tr -d '\n'` instead. – fedorqui Nov 03 '15 at 16:45
  • @fedorqui: 3.2.57(1)-release (x86_64-apple-darwin15). – orome Nov 03 '15 at 16:47
  • 1
    @raxacoricofallapatorius then, as I said, use `2>&1 |` instead of `|&`. – fedorqui Nov 03 '15 at 16:51
  • Trimming the newlines is unnecessary when the standard error is correctly copied to standard output first. `echo "$(python --version 2>&1) and more text"`. – chepner Nov 03 '15 at 18:21
  • @chepner yes, I noticed later that the `python --version` string was stderr and not stdout. I started just saying `echo "$(python --version | tr -d '\n') and more text"`, then I just left the `tr`. Updating but trying not to just have the same answer as glenn's. – fedorqui Nov 03 '15 at 21:36