1

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.

user_11077035
  • 113
  • 2
  • 9
  • 1
    You aren't executing the command in that second line. The command is executed in the first line and the results (stdout) are stored to the `GET_PODS_COMMAND` variable. Then you are merely setting the `GET_PODS_COMMAND_OUT` to the same value. Put that redirect `2>$1` on the backend of that `kubectl` command. You also have double quotes in your double quotes and since it's a wash anyway, just remove the double quotes around your `$()`. – JNevill Dec 11 '19 at 22:02
  • Tried this: GET_PODS_COMMAND="$(kubectl get pods -n mlsh-$JOBNAMESPACE --selector app=$POD_SELECTOR --template '{{range .items}}{{.metadata.name}}{{"\n"}}{{end}}' 2>&1)" echo $GET_PODS_COMMAND Result is still empty – user_11077035 Dec 11 '19 at 22:05
  • Try something like: `GET_PODS_COMMAND=$((kubectl get pods -n mlsh-$JOBNAMESPACE --selector app=$POD_SELECTOR --template '{{range .items}}{{.metadata.name}}{{"\n"}}{{end}}') 2>&1 )` – JNevill Dec 11 '19 at 22:09
  • Thanks, but still blank – user_11077035 Dec 11 '19 at 22:15
  • `GET_PODS_COMMAND_OUT="$(kubectl .... 2>&1)"` should be all you need.storing cmds to variables is fraught. Just use variables for input values that can change. Good luck. – shellter Dec 12 '19 at 01:59
  • were you able to get it to work? – alex Sep 22 '20 at 16:29

0 Answers0