![전역 변수 대신 배열을 실제 매개변수로 함수에 전달하는 방법](https://linux55.com/image/47653/%EC%A0%84%EC%97%AD%20%EB%B3%80%EC%88%98%20%EB%8C%80%EC%8B%A0%20%EB%B0%B0%EC%97%B4%EC%9D%84%20%EC%8B%A4%EC%A0%9C%20%EB%A7%A4%EA%B0%9C%EB%B3%80%EC%88%98%EB%A1%9C%20%ED%95%A8%EC%88%98%EC%97%90%20%EC%A0%84%EB%8B%AC%ED%95%98%EB%8A%94%20%EB%B0%A9%EB%B2%95.png)
배열을 매개변수 중 하나로 함수에 전달하는 방법이 있나요?
현재 나는
#!/bin/bash
highest_3 () {
number_under_test=(${array[@]})
max_of_3=0
for ((i = 0; i<$((${#number_under_test[@]}-2)); i++ )) {
test=$((number_under_test[i] +
number_under_test[i+1] +
number_under_test[i+2]))
if [ $test -gt $max_of_3 ]; then
max_of_3=$((number_under_test[i]+
number_under_test[i+1]+
number_under_test[i+2]))
result=$((number_under_test[i]))$((number_under_test[i+1]))$((number_under_test[i+2]))
fi
}
}
array=(1 2 3 4 5 6 7 8 7 6 5 4 3 2 1)
highest_3
echo result=$result
array=(1 2 3 4 3 2 1)
highest_3
echo result=$result
array
설정하고 사용하는 것만으로도 작동하지만 ( array
아마도 전역) 변수를 설정하는 대신 (1 2 3 4 5 4 3 2 1)과 같은 배열을 실제 매개 변수로 전달하는 방법이 있습니까?
업데이트: 이 배열 외에 다른 매개변수를 전달할 수 있기를 원합니다.
답변1
언제든지 배열을 함수에 전달하고 함수 내에서 배열로 재구성할 수 있습니다.
#!/usr/bin/env bash
foo () {
## Read the 1st parameter passed into the new array $_array
_array=( "$1" )
## Do something with it.
echo "Parameters passed were 1: ${_array[@]}, 2: $2 and 3: $3"
}
## define your array
array=(a 2 3 4 5 6 7 8 7 6 5 4 3 2 1)
## define two other variables
var1="foo"
var2="bar"
## Call your function
foo "$(echo ${array[@]})" $var1 $var2
위 스크립트는 다음과 같은 출력을 생성합니다.
$ a.sh
Parameters passed were 1: a 2 3 4 5 6 7 8 7 6 5 4 3 2 1, 2: foo and 3: bar
답변2
함수 내부의 매개변수를 배열로 읽을 수 있습니다. 그런 다음 이 매개변수를 사용하여 함수가 호출됩니다. 이와 같은 것이 나에게 효과적입니다.
#!/bin/bash
highest_3 () {
number_under_test=("$@")
max_of_3=0
for ((i = 0; i<$((${#number_under_test[@]}-2)); i++ )) {
test=$((number_under_test[i] +
number_under_test[i+1] +
number_under_test[i+2]))
if [ $test -gt $max_of_3 ]; then
max_of_3=$((number_under_test[i]+
number_under_test[i+1]+
number_under_test[i+2]))
result=$((number_under_test[i]))$((number_under_test[i+1]))$((number_under_test[i+2]))
fi
}
echo $result
}
highest_3 1 2 3 4 5 6 7 8 7 6 5 4 3 2 1
# or
array=(1 2 3 4 5 6 7 8 7 6 5 4 3 2 1)
highest_3 "${array[@]}"
답변3
문자열만 매개변수로 전달할 수 있습니다. 하지만 배열 이름을 전달할 수 있습니다.
highest_3 () {
arrayname="$1"
test -z "$arrayname" && exit 1
# this doesn't work but that is the idea: echo "${!arrayname[1]}"
eval echo '"${'$arrayname'[1]}"'
}