如何将一个参数传递给多个数组

时间:2019-01-09 10:33:04

标签: arrays bash

我希望我的bash脚本处理一个或多个附件。它们通过以下参数传递给脚本:

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

此参数存储在inputAttachments中。

如何将它们存储在以下数组中?

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

我的想法:我需要在每个分号处将inputAttachments分开,并在逗号处再次分开这些部分。但是如何完成并将其传递给数组。

1 个答案:

答案 0 :(得分:2)

我不确定,--attachment参数后如何捕获字符串。但是,一旦将其包含在shell变量中,您需要做的是两次遍历拆分,您可以使用bashread shell中完成,并通过设置{ {1}}值

IFS

使用此方法,字符串在IFS=\; read -r -a attachments <<<"hello,/dir/hello.pdf,pdf;image,/dir/image.png,png" 上分割并作为单独的元素存储在数组;中,您可以通过对数组名称进行attachments来可视化

declare -p

现在循环遍历数组并重新分割declare -p attachments declare -a attachments='([0]="hello,/dir/hello.pdf,pdf" [1]="image,/dir/image.png,png")' 上的元素并追加到单个数组

,