1

I'm trying to do prepare a script (.bat /.sh) with multiple commands and one of them is AWS Cli, and output of the execution has to be taken to a variable. If the command is executed succesfully, it is returning the output that is expected, otherwise error is printing on console rather than to variable.

Any leads on this would be appreciated

John Rotenstein
  • 241,921
  • 22
  • 380
  • 470
JASPHI
  • 133
  • 2
  • 10
  • Does this answer your question? [How do I set a variable to the output of a command in Bash?](https://stackoverflow.com/questions/4651437/how-do-i-set-a-variable-to-the-output-of-a-command-in-bash) – Biffen Jan 15 '21 at 13:44
  • @Biffen, no, actually i'm looking for an error related (like when the resource not exists) scenario. Error to be stored in variable rather than output – JASPHI Jan 15 '21 at 13:57
  • 2
    Have you considered using [Exit Codes](https://www.shellscript.sh/exitcodes.html)? – John Rotenstein Jan 16 '21 at 00:01
  • @JohnRotenstein, yes i used the exit codes – JASPHI Jan 18 '21 at 18:27

1 Answers1

0

Try below to redirect your standard error to the standard output and then store the standard output into the variable. This way you always get both so you can use $? to identify if the output is of type stderr or stdout aws cli return codes

get_user=$(aws iam get-user --user-name johnDoe 2>&1)
echo $?
echo "$get_user"

255
An error occurred (NoSuchEntity) when calling the GetUser operation: The user with name johnDoe cannot be found.
Dhirendra Khanka
  • 759
  • 1
  • 8
  • 21