Return strings and arrays from Bash functions. This is based on the excellent upvar
function.
Add to your bpm.ini
file the following dependency.
[dependencies]
assign=*
Run bpm install
to add the library. Finally, use it in your scripts.
#!/usr/bin/env bash
. bpm
bpm::include array
Send an array as a variable up to caller of a function. It is best used with some odd syntax as shown in the example, which preserves empty arrays.
- $1 - Variable name
- $2-@ - Array elements
Examples
callFunc () {
local myArray=(one two three)
local "${1-}" && assign::array "$1" ${myArray[@]+"${myArray[@]}"}
}
callFunc dest
echo "${dest[@]}" # writes "one two three"
Returns nothing.
Assigns a value by reference.
- $1 - Destination variable name.
- $2 - Source variable name.
Copies an array or scalar to the destination. This can be much simpler than assigning arrays. See the example for further information.
Examples
# Copy a value
a="a string"
assign::byRef b a
echo "$b" # "a string"
# Copy an array with an unknown number of elements (even zero)
# Replace "..." with zero or more elements.
theArray=( ... )
assign::byRef theArrayCopy theArray
set | grep ^theArray
# This shows the array was copied
# Copies an unset value as well.
unset unsetValue
unsetValueCopy=something
assign::byRef unsetValueCopy unsetValue
set | grep ^unsetValue
# Neither shows up.
Returns nothing.
Assign stdin to a value, preserving all newlines and everything that is piped in.
- $1 - Variable name.
Examples:
# This assigns *all* output to the variable
assign::pipe output < <(ls)
# This does not; it trims the trailing newline.
output=$(ls)
# Do not use it this way because the later functions are spawned in
# subshells, thus can not really change the value how you want.
echo "DOES NOT WORK THIS WAY" | assign::pipe badExample
# Works with heredocs!
assign::pipe helpMessage <<'EOF'
This is my help message.
It can have "quotes", 'apostrophes' and `backticks`.
EOF
Send a variable up to the parent of the caller of this function.
- $1 - Variable name.
- $2 - Value to assign.
Examples
callFunc() {
local dest
dest="Just an example to prove the local variable is overwritten"
local "${1-}" && assign::value "$1" "the value"
}
dest="value from target scope, ignored"
callFunc dest
echo "$dest" # writes "the value"
Returns nothing.
This project is placed under an MIT License.