0

I have the following bash file

#!/usr/bin/env bash
echo "$1"
cmdcopy="kubectl get nodes -o json | jq -c '.items[] | select(.status.nodeInfo.osImage | contains(\"$1\"))' | jq -r .metadata.name"                                                                                                                                                                                                                            
echo $cmdcopy

old_nodes=`kubectl get nodes -o json | jq -c '.items[] | select(.status.nodeInfo.osImage | contains("$1"))' | jq -r .metadata.name`
echo $old_nodes

for node in $old_node
echo 'Doing something to $node'                                                                                                                                                                                                                                                                                                                                
done

If I run outside the result of cmdcopy, it all works good. But inside the script the result of echo $old_nodes is empty.

What am I missing here ?

Djoby
  • 602
  • 1
  • 6
  • 22
  • 2
    paste your script at https://shellcheck.net for validation/recommendation. – Jetchisel May 31 '23 at 22:32
  • 1
    Stay clear of legacy backtick-based command substitution syntax -- the modern `$()` form has fewer pitfalls (one of which is a change in how backslashes are interpreted within them). – Charles Duffy May 31 '23 at 22:32
  • What do you mean by "run outside the result of cmdcopy"? – Barmar May 31 '23 at 22:35
  • (and `for node in $old_node` runs afoul of [DontReadLinesWithFor](https://mywiki.wooledge.org/DontReadLinesWithFor)) – Charles Duffy May 31 '23 at 22:36
  • 2
    Also, `contains("$1")` isn't going to be interpreted inside single quotes. Use `jq --arg` to pass arguments from bash to jq; don't substitute data into code. (That's not just jq advice; substituting data into code is bad form in pretty much _any_ language). – Charles Duffy May 31 '23 at 22:36

0 Answers0