-1

I am trying to write some conditional script to up my kubernetes system

#!/bin/sh

#checking if the namespace exists
export namespace="kube-system"
export mypassword="logan"
#installing json reader
echo mypassword | sudo apt-get install jq
echo mypassword | status=$(sudo kubectl get ns ${namespace} -o json | jq .status.phase -r)
echo "$status" #its not printing

if [ "$status" = "Active" ]
then
   echo hi
else
  echo bye
fi

But some how my status variable is not getting printed and neither the if else condition is working ,how to solve it ?Please help

john doe
  • 21
  • 3

2 Answers2

2

Your status assignment (status=$(...)) is happening in a subprocess (the one forked to receive the output of echo mypassword). So any changes wont reach the running shell.

You need something like:

# execute a command in a subprocess and capture all output in `status`
status=$(echo ... | sudo kubectl ... | jq ...)
if [ "$status" == 'active' ]
then
   echo 'active'
else
   echo 'not active'
fi
Cyrus
  • 84,225
  • 14
  • 89
  • 153
Michail Alexakis
  • 1,405
  • 15
  • 14
0

You could as well test the value with jq directly. When given the -e option, jq turns boolean values to exit status.

echo "$mypassword" | sudo kubectl get ns "$namespace" -o json | 
if jq -e '.status.phase == "Active"' >/dev/null
then
  echo hi
else
  echo bye
fi
Léa Gris
  • 17,497
  • 4
  • 32
  • 41