Home > Net >  Unable to store Azure CLI error output to a variable
Unable to store Azure CLI error output to a variable

Time:10-23

I tried to make some changes to Azure existing environment using Azure CLI. For success requests I am able to pull the required details using "--query", but for failed request I am not able to capture the output to variable.

Eg: az group show -n "rgname"

output: (ResourceGroupNotFound) Resource group 'rgname' could not be found

How to capture this error output to a variable.

CodePudding user response:

PowerShell write the messages to different streams that you can redirect e. g. to the standard output stream:

$output = (az group show -n "rgname" 2>&1)

Now $output will contain both - error messages and the regular output.

Alternative, you could redirect error messages to a file:

az group show -n "rgname" 2>error.log

See also: https://stackoverflow.com/a/17421207/1163423

CodePudding user response:

When a program is executed, three file handles are opened in this order: stdin, stdout and stderr. These file handles have numbers: 0, 1 and 2. This will help explain what 2>&1 does (redirects stderr to stdin).

Most programs, but not all, write error messages to stderr.

To capture stderr to a variable:

error=$(myprogram 2>&1 > /dev/null)

That example first redirects stdout to /dev/null and then redirects stderr to stdout. That output is then captured in the variable error.

If you also want to capture normal stdout messages:

error=$({myprogram > tmpfile;} 2>&1)
messages=$(<tmpfile)
rm tmpfile
  • Related