Search code examples
bashgithubhub

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


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.


Solution

  • 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 )