0

So I have my CSV file which looks like that:

repo_name1,path1,branch1 branch2

I read it with following code:

INPUT=repos.csv
OLDIFS=$IFS
IFS=','

[ ! -f $INPUT ] && { echo "$INPUT file not found"; exit 99; }
while read repo_name local_path branches
do
    printf "\n"
    echo "Repository name: $repo_name"
    echo "Local path: $local_path"
    cd $local_path
    for branch in $branches
    do
        echo branch
        printf "\n"
    done
done < $INPUT
IFS=$OLDIFS

And I want to split branch1 and branch2 to an array in bash script.

I tried everything that I found on stackoverflow Loop through an array of strings in Bash?, Split string into an array in Bash, Reading a delimited string into an array in Bash , but nothing is working correctly and what I'm getting is array containing 1 element -> branch1 branch2

Any ideas what I'm doing wrong?

cropyeee
  • 23
  • 1
  • 3
  • 1
    You have set `IFS=','` and trying to read space-separated array – Digvijay S Jul 16 '20 at 14:55
  • Try `IFS=",$IFS"` to add the comma but keep the usual delimiters. (and `echo branch` should probably be `echo "$branch"`.) – Paul Hodges Jul 16 '20 at 15:10
  • `for branch in $branches` -- you are using IFS=, to split `$branches`, there are no commas in $branches so you only get one iteration through that loop. – glenn jackman Jul 16 '20 at 15:31

1 Answers1

1

You have to do this in two steps:

input=repos.csv

while IFS=, read -r repo path branchstr; do
    read -ra branches <<< "$branchstr"
    declare -p repo path branches
done < "$input"

resulting in

$ ./split
declare -- repo="repo_name1"
declare -- path="path1"
declare -a branches=([0]="branch1" [1]="branch2")
Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
  • Thank you, that worked for me. Can you tell me how to get rid of this "declare" output? – cropyeee Jul 17 '20 at 06:50
  • @cropyeee It's the output of the `declare` command – an easy way to see what a variable contains. Just replace the `declare` line with whatever you want to do with `repo`, `path` and `branches`. – Benjamin W. Jul 17 '20 at 13:17