使用数组参数创建bash选择菜单 [英] Create bash select menu with array argument

查看:71
本文介绍了使用数组参数创建bash选择菜单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 createmenu 的函数。该函数将数组作为第一个参数。第二个参数是数组的大小。

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.

然后,我想使用该数组的元素创建一个选择菜单。这就是我到目前为止所拥有的:

I then want to create a select menu using the elements of that array. This is what I have so far:

createmenu ()
{
  echo $1
  echo "Size of array: $2"
  select option in $1; do
    if [ $REPLY -eq $2 ];
    then
      echo "Exiting..."
      break;
    elif [1 -le $REPLY ] && [$REPLY -le $2-1 ];
    then
      echo "You selected $option which is option $REPLY"
      break;
    else
      echo "Incorrect Input: Select a number 1-$2"
    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?

推荐答案

我的建议是反转参数的顺序(尽管您不这样做)甚至不需要长度参数,但我们会讲到这一点),然后将数组作为位置参数传递给函数。

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.

createmenu ()
{
  arrsize=$1
  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.

如果您正在使用数组元素的位置参数,那么您已经在...中使用了长度... $#,就可以使用它。 / p>

If you are using the positional parameters for the array elements then you already have the length... in $# and can just use that.

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[@]}"

这篇关于使用数组参数创建bash选择菜单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆