Simon
Simon

Reputation: 433

How to pass one argument into multiple arrays

I want my bash script to process one or multiple attachments. They're passed to the script by the following parameter:

--attachment "filename(1),pathtofile(1),fileextension(1);[...];filename(n),pathtofile(n),fileextesion(n)"
--attachment "hello,/dir/hello.pdf,pdf;image,/dir/image.png,png"

This argument is stored in inputAttachments.

How can I store them in the following array?

attachmentFilename=("hello" "image")
attachmentPath=("/dir/hello.pdf" "/dir/image.png")
attachmentType=("pdf" "png")

My thought: I need to seperate inputAttachments at every semicolon and split those parts again at the comma. But how is this done and passed into the array.

Upvotes: 1

Views: 44

Answers (1)

Inian
Inian

Reputation: 85550

I'm not exactly sure, how you are capturing the string after --attachment argument. But once you have it in a shell variable, all you need is a two-pass split which you can accomplish in the bash shell using read and a custom de-limiter to split on by setting the IFS value

IFS=\; read -r -a attachments <<<"hello,/dir/hello.pdf,pdf;image,/dir/image.png,png"

With this the string is split on ; and stored in the array attachments as individual elements which you can visualize by doing declare -p on the array name

declare -p attachments
declare -a attachments='([0]="hello,/dir/hello.pdf,pdf" [1]="image,/dir/image.png,png")'

Now loop over the array and re-split the elements on , and append to individual arrays

for attachment in "${attachments[@]}"; do
    IFS=, read -r name path type <<<"$attachment"
    attachmentFilename+=( "$name" )
    attachmentPath+=( "$path" )
    attachmentType+=( "$type" )
done

Upvotes: 2

Related Questions