Reputation: 691
I am trying to do a kubectl exec and store value into a variable. But the variable displays null. If i use -it in the exec, it works. Since while running with terraform says can't allocate terminal, I need to run it without -it.
Command I run: abc=$(kubectl exec nginx-6799fc88d8-xpzs9 -- nginx -v)
Upvotes: 0
Views: 4396
Reputation: 928
As @P.... Mentioned alternative approach for replacing -it is using 2>&1
Here is one way to remember this construct: at first, 2>1 may look like a good way to redirect stderr to stdout. However, it will actually be interpreted as "redirect stderr to a file named 1". & indicates that what follows and precedes is a file descriptor and not a filename. So the construct becomes: 2>&1.
Consider >& as a redirect merger operator.
For more details, refer this document on kubectl exec command.
Upvotes: 0
Reputation: 18411
You need to modify your command as following(-it
):
abc=$(kubectl exec -it nginx-6799fc88d8-xpzs9 -- nginx -v)
The reason for this behavior is nginx -v
is displaying the output over stderr
not stdout
. This means, the command you were using would work for any other commands like ls
, cat
etc which display output over stdout
.
Alternate approach by redirecting stderr to stdout(2>&1
) :
abc=$(kubectl exec nginx-6799fc88d8-xpzs9 -- nginx -v 2>&1)
Example:
x=$(k exec nginx -- nginx -v 2>&1)
echo "$x"
nginx version: nginx/1.21.3
Upvotes: 2