Issue
Ordinarily, running a command as $(command)
discards any trailing newlines produced by command
. However, when I run this command:
output=$(kcadm get users)
I always get a newline echoed. Why, and how can I get rid of it? It doesn't make any difference if I do this, or an equivalent:
output=$(kcadm get users) > /dev/null 2>&1
kcadm
is an alias to a shell script, which runs Java and produces JSON output. If I run the script directly, I can always completely suppress any output from it (kcadm get users > /dev/null 2>&1
), but I of course need to record the output for analysis.
EDIT
Before anyone else jumps in with a close vote, please: the bash manual says that "trailing newlines are deleted" in $()
command substitution. The suggested answer is not, AFAICT, relevant.
YET ANOTHER EDIT
The suggested answer is for an entirely different question, and simply handles obvious cases where a substitution on the output removes a newline. This question is about a situation where the newline shouldn't have happened in the first place, and what caused it. This really should have been obvious to the close voters.
Solution
Assumptions:
- when OP says
I always get a newline echoed
, this is in reference to the output fromoutput=$(kcadm get users)
and not the result ofecho "$output"
Without more debugging details I'm going to guess that kcadm
is sending a single blank line to stderr.
If this is the case then the stderr output is not captured by OP's current command - output=$(kcadm get users)
- but rather passed to the terminal.
A simple test/fix would be to redirect kcadm
's stderr to stdout, eg:
output=$(kcadm get users 2>&1)
Answered By - markp-fuso Answer Checked By - Timothy Miller (WPSolving Admin)