1

Below command is running on linux system and I want to save output as list.

root@Linux:~ kubectl get ns | awk '{print $1}'     
NAME
b2
b6
b7
cert-manager

I need to save above command output in to variable as list.

Example:- 
NAMESPACE = ['NAME', 'b2', 'b6', 'b7', 'cert-manager']

NAMESPACE is variable
me25
  • 497
  • 5
  • 18
  • Does this answer your question? [Reading output of a command into an array in Bash](https://stackoverflow.com/questions/11426529/reading-output-of-a-command-into-an-array-in-bash) – Shubhzgang May 15 '20 at 10:39
  • I am not sure to understand your question. Do you want to implement a command that is setting the variable `NAMESPACE` to the string `['NAME', 'b2', 'b6', 'b7', 'cert-manager']`, quotes, spaces and brackets included, or do you want to create a bash array `NAMESPACE` having as elements the 5 items you got above without quotes, brackets, spaces and newlines? – Pierre François May 15 '20 at 10:55
  • I need "kubectl get ns | awk '{print $1}' command out put as NAMESPACE(this could be any name) = ['NAME', 'b2', 'b6', 'b7', 'cert-manager'] – me25 May 15 '20 at 11:12
  • @PierreFrançois this is the one i am looking "NAMESPACE to the string ['NAME', 'b2', 'b6', 'b7', 'cert-manager'], quotes, spaces and brackets included" – me25 May 15 '20 at 11:15
  • @Cyrus If possible can you explain the command ? – me25 May 15 '20 at 12:02

2 Answers2

1

If the output includes only simple words you can write like this:

$ arr=( $( echo a b c d ) )
$ for i in "${arr[@]}"; do echo "$i"; done
a
b
c
d
$ arr=$( echo a b c d )
$ for i in $arr; do echo "$i"; done
a
b
c
d
$
0

It is rather tricky because of the mix of quotes and double quotes where some need to be escaped, anyway next command appears to work:

NAMESPACE=$(kubectl get ns | awk 'NR == 1{o = "['\''" $1 "'\''"}NR > 1{o = o ", '\''" $1 "'\''"}END{o = o "]"; print o}')

With your input, this gives me:

$ echo "$NAMESPACE"
['NAME', 'b2', 'b6', 'b7', 'cert-manager']
Pierre François
  • 5,850
  • 1
  • 17
  • 38