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?

3
  • 1
    You have set IFS=',' and trying to read space-separated array Commented Jul 16, 2020 at 14:55
  • Try IFS=",$IFS" to add the comma but keep the usual delimiters. (and echo branch should probably be echo "$branch".) Commented Jul 16, 2020 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. Commented Jul 16, 2020 at 15:31

1 Answer 1

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

2 Comments

Thank you, that worked for me. Can you tell me how to get rid of this "declare" output?
@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.

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.