我想编写一个函数,它接受一个数组变量名并更新内容。例如:
ARRAY1=("test 1" "test 2" "test 3")
toUpper ARRAY1
for arg in "${ARRAY1[@]}"; do
echo "arg=$arg"
done
# output
arg=TEST 1
arg=TEST 2
arg=TEST 3
我做了一个粗略的尝试,这需要输入数组的副本。使用间接引用,我能够创建输入变量的副本。数组的副本用于获取元素的计数。如果有更好的方法来做到这一点,请告诉我。
function toUpper() {
local ARRAY_NAME=$1
local ARRAY_REF="$ARRAY_NAME[@]"
# use an indirect reference to copy the array so we can get the count
declare -a ARRAY=("${!ARRAY_REF}")
local COUNT=${#ARRAY[@]}
for ((i=0; i<$COUNT; i++)); do
local VAL="${ARRAY[$i]}"
VAL=$(echo $VAL | tr [:lower:] [:upper:])
echo "ARRAY[$i]=\"$VAL\""
eval "$ARRAY_NAME[$i]=\"$VAL\""
done
}
ARRAY1=( "test" "test 1" "test 3" )
toUpper ARRAY1
echo
echo "Printing array contents"
for arg in "${ARRAY1[@]}"; do
echo "arg=$arg"
done