使用数组参数创建 bash 选择菜单
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28325915/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Create bash select menu with array argument
提问by honestemu3
I have a function called createmenu
. This function will take in an array as the first argument. The second argument will be the size of the array.
我有一个名为createmenu
. 此函数将接受一个数组作为第一个参数。第二个参数是数组的大小。
I then want to create a select menu using the elements of that array. This is what I have so far:
然后我想使用该数组的元素创建一个选择菜单。这是我到目前为止:
Create the menu with the given array
使用给定的数组创建菜单
createmenu ()
{
echo
echo "Size of array: "
select option in ; do
if [ $REPLY -eq ];
then
echo "Exiting..."
break;
elif [1 -le $REPLY ] && [$REPLY -le -1 ];
then
echo "You selected $option which is option $REPLY"
break;
else
echo "Incorrect Input: Select a number 1-"
fi
done
}
This is an example call to the function:
这是对该函数的示例调用:
createmenu ${buckets[*]} ${#buckets[@]}
How do I create this select menu using the elements of the argument array as options?
如何使用参数数组的元素作为选项创建此选择菜单?
回答by Etan Reisner
My suggestion would be to invert the order of your arguments (though you don't even need the length argument but we'll get to that) and then pass the array as positional parameters to the function.
我的建议是反转参数的顺序(尽管您甚至不需要 length 参数,但我们会解决这个问题),然后将数组作为位置参数传递给函数。
createmenu ()
{
arrsize=
echo "Size of array: $arrsize"
echo "${@:2}"
select option in "${@:2}"; do
if [ "$REPLY" -eq "$arrsize" ];
then
echo "Exiting..."
break;
elif [ 1 -le "$REPLY" ] && [ "$REPLY" -le $((arrsize-1)) ];
then
echo "You selected $option which is option $REPLY"
break;
else
echo "Incorrect Input: Select a number 1-$arrsize"
fi
done
}
createmenu "${#buckets[@]}" "${buckets[@]}"
Note I also fixed a couple of errors in your function. Namely that you'd missed some spaces between [
and the first argument and that [
isn't an arithmetic context so you need to force one for your math to work).
注意我还修复了您函数中的几个错误。也就是说,您[
在第一个参数和第一个参数之间错过了一些空格,并且这[
不是算术上下文,因此您需要强制一个空格才能使您的数学工作)。
But back to my comment before about not needing the length argument at all.
但是回到我之前关于根本不需要长度参数的评论。
If you are using the positional parameters for the array elements then you already have the length... in $#
and can just use that.
如果您正在使用数组元素的位置参数,那么您已经拥有长度... in$#
并且可以使用它。
createmenu ()
{
echo "Size of array: $#"
echo "$@"
select option; do # in "$@" is the default
if [ "$REPLY" -eq "$#" ];
then
echo "Exiting..."
break;
elif [ 1 -le "$REPLY" ] && [ "$REPLY" -le $(($#-1)) ];
then
echo "You selected $option which is option $REPLY"
break;
else
echo "Incorrect Input: Select a number 1-$#"
fi
done
}
createmenu "${buckets[@]}"