-1

bash noob here. I have a bash command that if I execute as normal from the command line returns an ip address:

kubectl get svc ssdl-web --namespace default -o jsonpath='{$.status.loadBalancer.ingress[0].ip}'

returns:

104.76.131.131

However if I store the command in a var and then execute it the answer comes back wrapped in apostrophes:

get_external_ip_cmd="kubectl get svc ssdl-web --namespace default -o jsonpath='{$.status.loadBalancer.ingress[0].ip}'" && echo $($(echo $get_external_ip_cmd))

'104.76.131.131'

I need the result without the apostrophes.

I'm sure there's a simple explanation but I haven't a clue what. Can anyone fill me in? thx.

(My reason for storing the command in a var is that I want to execute it multiple times)

jamiet
  • 10,501
  • 14
  • 80
  • 159
  • 2
    Don't store shell commands in string variables -- use functions for that. See [BashFAQ #50](http://mywiki.wooledge.org/BashFAQ/050). Only a small subset of shell parsing steps are run on parameter expansion or command substitution results (for good reason; there would be massive security vulnerabilities in shell languages if referring to variables containing data, or commands generating data as their output, parsed that data as code). – Charles Duffy Dec 20 '18 at 18:32
  • fair enough. will do. – jamiet Dec 20 '18 at 18:33

1 Answers1

1

Substitution results only go through string-splitting and glob-expansion. They don't go through quote removal (quotes are treated as literal, not syntactic), so the quotes are passed to your command rather than consumed by the shell.

This is discussed in detail in BashFAQ #50. Best practice is generally to use functions, not strings, to store code intended to be called multiple times. (In some circumstances arrays may be more appropriate instead; read the FAQ for details).


Defining a function with your code looks like:

get_external_ip() {
  kubectl get svc ssdl-web \
    --namespace default \
    -o jsonpath='{$.status.loadBalancer.ingress[0].ip}'
}

Then run it as:

get_external_ip
Charles Duffy
  • 280,126
  • 43
  • 390
  • 441