Contents
Can you pass an array to a function in Bash?
You cannot pass an array, you can only pass its elements (i.e. the expanded array). You can pass an array by name reference to a function in bash (since version 4.3+), by setting the -n attribute: See also nameref or declare -n in the man page. You could pass the “scalar” value first.
How to convert command line arguments into array in Bash?
I need to convert the arguments into a regular bash script array; I realize I could use other languages (Python, for instance) but need to do this in bash. I guess I’m looking for an “append” function or something similar?
When to use an array as an argument?
For your specific case, this could be used (without the need for arrays), to set the list of arguments when none was given: The importance of the double quotes is worth emphasizing. Suppose an argument contains whitespace.
How to convert a variable into an array?
At least, you can treat the $@ variable much like an array. That said, you can convert it into an actual array like this: If you just want to type some arguments and feed them into the $@ value, use set:
How to pass an array as an argument to a function?
Here is one example: As described, function f receives two arguments: the first is assigned to x which is an array, the second to y. f can be called in two ways. The first way use the “$ {a [@]}” as the first argument, and the result is: The second way use the “$ {a [*]}” as the first argument, and the result is: Neither result is as I wished.
How to convert arguments into an array in POSIX?
If you just want to type some arguments and feed them into the $@ value, use set: Understanding how to use the argument structure is particularly useful in POSIX sh, which has nothing else like an array. For your specific case, this could be used (without the need for arrays), to set the list of arguments when none was given: