cosmos-1905-14
cosmos-1905-14

Reputation: 1323

How can I split string to navigate in for loop?

I am not so familiar with bash scripting. I want to echo each line with the proper format role path=... but this for loop does not allow me to do so. It basically prints all in once not go line by line prints. But interestingly when I run vault list database/roles command I am able to see all roles line by line.

How can I resolve this problem?

Code:

for path in $(vault list database/roles);
do
    echo role path=${path}; 
done

Output:

role path=Keys
----
Role-1
Role-2
Role-3
Role-4
Role-5

P.S.: I need to keep everything in the loop as I am going to run this command later on: vault delete database/roles/${path}

Updated: Output for vault list database/roles

Keys ---- Role-1 Role-2 Role-3 Role-4 Role-5

Thanks!

Upvotes: 0

Views: 75

Answers (1)

markp-fuso
markp-fuso

Reputation: 34916

Assuming the output from vault list database/roles looks like:

Keys
----
Role-1
Role-2
Role-3
Role-4
Role-5

OP mentions 'keep it in the array', but there are no signs of an array anywhere in OP's current code; at this point I'm going to assume the intention is to store the output of the vault command in an array.

One idea for storing the roles (aka vault output) in an array:

mapfile -t roles < <(vault list database/roles | tail +3)

This will create and populate an array named roles like such:

$ typeset -p roles
declare -a roles=([0]="Role-1" [1]="Role-2" [2]="Role-3" [3]="Role-4" [4]="Role-5")

From here OP can loop through the array like such:

for ((i=0; i<"${#roles[@]}"; i++))
do
    echo "${i} : ${roles[${i}]}"
done

# or

for i in "${!roles[@]}"
do
    echo "${i} : ${roles[${i}]}"
done

Both of these loops generate:

0 : Role-1
1 : Role-2
2 : Role-3
3 : Role-4
4 : Role-5

Upvotes: 1

Related Questions