Home > Enterprise >  How to loop names with spaces in bash script?
How to loop names with spaces in bash script?

Time:11-11

I'm having a python list output:

names=[Raj Sonakshi, Getendar, Raghu Varan (Mr)]

I run python script using the below bash command

arr=$(python names.py)

Output I got is:

Raj Sonakshi Getendar Raghu Varan (Mr)

When I run for loop each word is printing instead of full name:

for i in $arr;
do 
  echo $i
done

Output:

Raj
Sonakshi
.....
.....

Expected Output is :

Raj Sonakshi

CodePudding user response:

Put the names in the array in quotes

names=["Raj Sonakshi", "Getendar", "Raghu Varan (Mr)"]

CodePudding user response:

Not sure what your python script's output looks like exactly; the "output" in your question seems to be after bash has turned it into one long string. And you probably don't want it to be a string (as you are doing with arr=$()), but rather you probably want to use a bash array:

declare -a arr
readarray -t arr <<< "$(python names.py)"
for i in "${arr[@]}"; do
  echo "$i"
done
  • Related