0

I have a bash script with following variable:

operators_list=$'andrii,bogdan,eios,fre,kuz,pvm,sebastian,tester,tester2,vincent,ykosogon'

while IFS=, read -r tech_login; do


    echo "... $tech_login ..."

done <<< "$operators_list"

I need to read arguments from variable and work with them in loop. But it returns echo only one time with all items:

+ IFS=,
+ read -r tech_login
+ echo '... andrii,bogdan,eios,fre,kuz,pvm,sebastian,tester,tester2,vincent,ykosogon ...'
... andrii,bogdan,eios,fre,kuz,pvm,sebastian,tester,tester2,vincent,ykosogon ...
+ IFS=,
+ read -r tech_login

What am I doing wrong? How to rework script, so it will work only with one item per time?

1 Answer 1

1
operators_list=$'andrii,bogdan,eios,fre,kuz,pvm,sebastian,tester,tester2,vincent,ykosogon'

So you have strings separated by ,. You can do that multiple ways:

  1. using bash arrays:

IFS=, read -a operators <<<$operators_list
for op in "${operators[@]}"; do
    echo "$op"
done
  1. Using a while loop, like you wanted:

while IFS= read -d, -r op; do
    echo "$op"
done <<<$operators_list
  1. Using xargs, because why not:

<<<$operators_list xargs -d, -n1 echo

The thing with IFS and read delimeter is: read reads until delimeter specified with -d. Then after read has read a full string (usually whole line, as default delimeter is newline), then the string is splitted into parts using IFS as delimeter. So you can:

while IFS=: read -d, -r op1 op2; do
    echo "$op1" "$op2"
done <<<"op11:op12,op12:op22"
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! Forgot about -d, as delimiter!
note that the read exit status for last element is not 0, but could be handled : while IFS= read -d, -r op; [[ $op ]]; do ... but this would stop on first empty element otherwise while IFS= read -d, -r op || [[ $op ]]; do ..., howvwer for the last item would contain the final \n due to here string

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.