Score:5

Use an array as argv?

si flag

In a bash script, I'm calling a function with a large number of arguments, say for example /bin/meaningoflife takes 42 arguments. Is there a way I can pass an array to a command instead of manually entering in all of the 42 arguments? For example:

arr = ("arg1", "arg2", "arg3")
/bin/meaningoflife {argv=arr}

is the same as

/bin/meaningoflife "arg1" "arg2" "arg3"

Thanks!

Score:10
hr flag

The bash syntax would be

arr=("arg1" "arg2" "arg3")          # no commas, no whitespace around the assignment
/bin/meaningoflife "${arr[@]}"      # double quotes prevent word splitting of elements

More formally, rather than "no commas" in the assignment, you want array elements to be separated by whitespace. It would be equally valid to write

arr=(
  "arg1"
  "arg2"
  "arg3"
)

for example - which is often easier to read for long lists.

See Arrays (Bash Reference Manual)

cn flag
Even if IFS is set to comma, that only affects word splitting after variable expansion, not when parsing the script source itself.
hr flag
@Barmar thanks - for some reason, I was thinking IFS affected the parsing of the compound assignment
I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.