Because of the need to use the shell to develop a number of gadgets, when using an array as a function parameter, found that only the first element of the array can be passed, the elements behind the array can not be passed into the function.
#!/bin/bash
function Showarr () {
arr=$1 for I-in
${arr[*]}; does
echo $i done
}
regions= (" GZ "" SH "" BJ "
showarr $regions
exit 0
After the code is saved as test.sh, only the first element is exported.
./test.sh
GZ
To get the first argument of the function, and the first argument of the function is the regions array, it's strange why you can only get the first element of the array.
After testing,
Echo $regions
Only the first element is output, so using regions as a parameter passes only the first element.
Therefore, the argument needs to be written "${regions[*]}" to be passed as an array.
The code is modified as follows:
#!/bin/bash
function Showarr () {
arr=$1 for I-in
${arr[*]}; does
echo $i done
}
regions= ("GZ" "SH" "BJ")
Showarr "${regions[*]}"
exit 0
After running all elements of an array, the array can be passed as a function parameter after modification.
./test.sh
GZ
sh
BJ