0

I need to assign multiline output of command to a variable. I read these two threads:

assigning the output of a command to a variable in a shell script

Capturing multiple line output into a Bash variable

and it works for echo example (multiline commands):

#!/bin/bash
output="$( bash <<EOF
echo first
echo second
echo third
EOF
)"
echo "$output"

but it seems to not working for one command with multiline output. When I run

output="$( bash <<EOF
echo abc
uncrustify -c ~/.uncrustify.cfg --check filename
echo def
EOF
)"

I will receive the second line of default uncrustify -c ~/.uncrustify.cfg --check filename output:

FAIL: filename (File size changed from 404 to 417)

Default output for uncrustify -c ~/.uncrustify.cfg --check filename is:

Parsing: filename as language OC
FAIL: filename (File size changed from 404 to 417)

I want to assign both of these lines to output variable and hide all outputs to console.

Piotr Wasilewicz
  • 1,751
  • 2
  • 15
  • 26

1 Answers1

0

Why not try:

output=`echo abc && uncrustify -c ~/.uncrustify.cfg --check filename && echo def`

Or better yet, to get the variable to store new lines:

output="$(echo abc)\n$(uncrustify -c ~/.uncrustify.cfg --check filename 2>&1)\n$(echo def)"
echo -e "$output"

Please note the -e flag used with echo, as this enables it to translate the \n sequence into a newline.

AnythingIsFine
  • 1,777
  • 13
  • 11
  • I created script.sh and added `output="$(echo abc)\n$(uncrustify -c ~/.uncrustify.cfg --check filename)\n$(echo def)"` in it (without echo line). I run script in console by ./script.sh and got `FAIL: filename (File size changed from 404 to 417)` to console what I did not want. – Piotr Wasilewicz Jan 29 '18 at 12:06
  • The same with your first option. – Piotr Wasilewicz Jan 29 '18 at 12:12
  • I realised that `FAIL: filename (File size changed from 404 to 417)` is a text from `stderr`. How to put also it to variable? – Piotr Wasilewicz Jan 29 '18 at 12:28
  • This is because of your script prints to stderr, you should apply the line from my edited answer. – AnythingIsFine Jan 29 '18 at 12:28