I am executing a kubectl command in a bash script and storing the output in a variable. When the kubectl command executes successfully I am getting the correct output in the variable, but when it does not execute successfully the variable is empty and the error message is not available in the variable. I want the error values to be stores in the variable.
Example:
GET_PODS_COMMAND="$(kubectl get pods -n mlsh-$JOBNAMESPACE --selector app=$POD_SELECTOR --template '{{range .items}}{{.metadata.name}}{{"\n"}}{{end}}')" #kubectl command. Please assume mlsh-$JOBNAMESPACE and $POD_SELECTOR have correct values
GET_PODS_COMMAND_OUT=$GET_PODS_COMMAND
echo $GET_PODS_COMMAND_OUT #Printing command result
When the command execution is successful I get the pod name in GET_PODS_COMMAND_OUT but when the command output is "No Resources Found" value for GET_PODS_COMMAND_OUT is blank.
I read that I have to redirect the stderr to stdout as stated in below articles: Bash how do you capture stderr to a variable? https://www.reddit.com/r/kubernetes/comments/98s8v6/why_cant_i_store_outputs_of_kubectl_commands_in_a/
Still struggling to understand how exactly to achieve this. Here is what I have tried:
GET_PODS_COMMAND_OUT="$(GET_PODS_COMMAND 2>&1)" #gives the error: GET_PODS_COMMAND: command not found
New to linux so any help is appreciated. Thank you.