Home > Blockchain >  How to store multiline outputs from 'hub' command in a variable?
How to store multiline outputs from 'hub' command in a variable?

Time:11-16

If I use the hub command to create a pull request on GitHub and I get an error then it is outputted on four lines:

hub pull-request -p -b MyOrg:main -h Test_Branch -m "testing" 

output:

Everything up-to-date
Branch 'Test_Branch' set up to track remote branch 'Test_Branch' from 'MyOrg'.
Error creating pull request: Unprocessable Entity (HTTP 422)
A pull request already exists for MyOrg:Test_Branch.

Now if I try to store the output this way:

output=$(hub pull-request -p -b MyOrg:main -h Test_Branch -m "testing")

then oddly enough only the second line is stored in output.

If I print it I see only the second line:

echo $output

result:

Branch 'Test_Branch' set up to track remote branch 'Test_Branch' from 'MyOrg'.

My overall goal is to capture the output and not have it printed to the user. I just want to show them a simple error message (instead of four lines of output). Ideally, I just want to do grep on Error creating pull request and based on that print a dedicated error message.

Can anybody tell me how to do this? Thanks.

CodePudding user response:

Based on the comment from @mivk which is the correct answer I posted this answer:

I would guess that the other lines go to STDERR? To keep both STDOUT and STDERR, try adding 2>&1 at the end: output=$(hub ..."testing" 2>&1)

CodePudding user response:

The other lines are probably printed to STDERR. When using command substitution, only STDOUT is captured into the vraiable.

To get both, you need to redirect STDERR to STDOUT by appending 2>&1 to your command:

output=$( your_command 2>&1 )
  • Related