How the shell uses an array as a function parameter
Due to work needs, I need to use the shell to develop some small tools. When using an array as a function parameter, I found that only the first element of the array can be passed, and the elements after the array cannot be passed to the function.
#!/bin/bash
function showArr(){
arr=$1
for i in ${arr[*]}; do
echo $i
done
}
regions=("GZ" "SH" "BJ")
showArr $regions
exit 0
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
Save the code as test.sh and execute it, only the first element is output.
./test.sh
GZ
- 1
- 2
$1 means to get the first parameter of the function, and the first parameter of the function is the regions array, so it is strange, why can only get the first element of the array?
tested,
echo $regions
- 1
Only the first element will be output, so using regions as a parameter will only pass the first element.
Therefore, the parameter needs to be written as "${regions[*]}" before it can be passed as an array.
The code is modified as follows:
#!/bin/bash
function showArr(){
arr=$1
for i in ${arr[*]}; do
echo $i
done
}
regions=("GZ" "SH" "BJ")
showArr "${regions[*]}"
exit 0
- 1
- 2
- 3
- 5
- 6
- 7
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
After running, all elements of the array are output, so the array can be passed as a function parameter after modification.
./test.sh
GZ
SH
BJ