'How to use $1 in ${} in shell script
function print_array(){
NUMBER=1
for i in ${$1[@]}; do
printf "%d: %s \n" $NUMBER $i
$((NUMBER++))
done
}
I want to write a function that can accept an array as a parameter and print all things inside the array.
So I wrote something like ${$1[@]}, and shell said that's a "bad substitution".
Any ways to achieve the same effect? Thanks!
Solution 1:[1]
There are several problems with this code, but the primary is one is that $1 will never be an array. If you want to pass an array to a function, you would need to do something like this:
print_array(){
NUMBER=1
for i in "${@}"; do
printf "%d: %s \n" $NUMBER "$i"
((NUMBER++))
done
}
myarray=(this is "a test" of arrays)
print_array "${myarray[@]}"
This will output:
1: this
2: is
3: a test
4: of
5: arrays
Note that the quoting in this script is critical: Writing ${myarray[@]} is not the same as writing "${myarray[@]}"; see the Arrays section of the bash manual for details, as well as the Special Parameters section for information about $@ vs "$@".
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | larsks |
