After seeing this question, I decided to put together a function to remove array empty elements in case it saves someone a few seconds.
Is there any way to return (or export) a dynamically named input array-variable as the output of a function?
Ideally
- User calls:
removeArrayBlanks "newArrayName" "arrayItem1" "" "arrayItem2"...
- The function unsets the old array and creates:
${newArrayName[@]}
, which expands to"arrayItem1" "arrayItem2"
without any blank items or non-sequential index numbers
Also, does anyone have any optimizations/suggestions to the function? I've included the function below. Thanks!
removeArrayBlanks() {
# Usage: Provide array as input, store output as array.
# Example 1: mapfile -t lastArray < <(removeArrayBlanks "hate" "" "empty" "array" "items")
# Example 2: mapfile -t lastArray < <(removeArrayBlanks "${inputArray[@]}")
[[ $# -lt 2 ]] && echo "Usage: Provide array as an argument." && exit 1 # Ensure input is array
tempArray=( "$@" ) # Rebuild array from inputs
for i in "${!tempArray[@]}"; do
[[ ! -z "${tempArray[$i]}" ]] && finalArray+=( "${tempArray[$i]}" ) # Add non-empty strings
done && printf '%s\n' "${finalArray[@]}" && unset tempArray && unset finalArray
}