2

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
5
  • Does this answer your question? Reading output of a command into an array in Bash Commented May 15, 2020 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? Commented May 15, 2020 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'] Commented May 15, 2020 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" Commented May 15, 2020 at 11:15
  • @Cyrus If possible can you explain the command ? Commented May 15, 2020 at 12:02

2 Answers 2

2

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
$
Sign up to request clarification or add additional context in comments.

Comments

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']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.