Search code examples
bashshellkubectl

Save kubectl command output in variable in Bashscript


Just want to save the output from a kubectl command in a variable in a Bash script.

For example: command kubectl get all -n mattermost outputs No resources found in mattermost namespace.

foo=$(kubectl get all -n mattermost)

while [ "$foo" = "No resources found in mattermost namespace." ]
do
  echo "yay"
done

Unfortunately the output won't save in the variable..


Solution

  • There are two problems with your script...

    1. The problem you described is because its an error message you try to catch but you catch normal massages only. Bash and other Shells use stdin stdout and stderr for messaging. With your command the variable will catch stdout only.
    • 2 = stderr
    • 1 = stdout
    • 0 = stdin
    • & = means some like add this to that
    • < > = where to go with stdxxx

    It should be more like ...

    foo=$(ANY COMMAND 2>&1)
    
    1. When you run the script it will create that variable first and after that the loop will be endless, cause there are no changes to that variable. Instead you could get rid of that variabe and put it in your loop.
    while [ "$(kubectl get all -n mattermost 2>&1)" = "No resources found in mattermost namespace." ]; do
    echo "Hello World"
    done
    

    This way your loop will stop when stderr or stdout will change. There is also the possibility to stop the loop with a break or stop the script with return or exit (depending on how you will run that script).