bashcommandprintfechosubstitution

Bash Command Substitution in echo/printf doesn't print result on the same line?


Reproducible example

Consider this example:

#!/usr/bin/env bash
echo "[Status] $(killall --wait example)"

Expected output:

[Status] example: no process found

Actual result (being wrong order and 2 lines):

example: no process found

[Status]

Workaround

result=$(killall --wait example 2>&1)
echo "[Status] ${result}"

Questions

  1. How come the output isn't on the same line in the reproducible example?
  2. Apart from the workaround, is there any way to await the result of command substitution and print it on the same line (e.g. perhaps via process substitution with pipes)?

Solution

  • Change:

    echo "[Status] $(killall --wait example)"

    into:

    echo "[Status] $(killall --wait example 2>&1)"

    Explanation: killall prints out on standard error instead of standard output.