パラメータの1つとして配列を関数に渡す方法はありますか?
現在私は持っています
#!/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)などの配列を渡す方法はありますか?
更新:この配列の横にある他のパラメーターを渡せるようにしたい
いつでも配列を関数に渡し、関数内の配列として再構築できます。
#!/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
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加