bash 在列表名称不固定时获取列表长度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21091522/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 09:14:13  来源:igfitidea点击:

bash get list length when list name is not fixed

bash

提问by Omer Dagan

Suppose I have two lists:

假设我有两个列表:

lista="a b c d"
listb="e f"

I would like to write a function that returns the number of items on a given list:

我想编写一个函数来返回给定列表中的项目数:

>>foo $lista
4
>>foo $listb
2

I've tried using ${#<varname>[@]}syntax, also ${#!<varname>[@]}, unsuccessfully.

我也尝试过使用${#<varname>[@]}语法,${#!<varname>[@]}但没有成功。

Thanks

谢谢

回答by fedorqui 'SO stop harming'

You can use wc -wfor this:

您可以wc -w为此使用:

$ lista="a b c d"
$ wc -w <<< "$lista"
4
$ listb="e f"
$ wc -w <<< "$listb"
2

From man wc:

来自man wc

-w, --words

print the word counts

-w, --words

打印字数



To make it function, use:

要使其发挥作用,请使用:

list_length () {
        echo $(wc -w <<< "$@")
}

And then you can call it like:

然后你可以这样称呼它:

list_length "a b c"

回答by anubhava

Put them into BASH array and look at array length.

将它们放入 BASH 数组并查看数组长度。

a=($lista)
echo ${#a[@]}
4

a=($listb)
echo ${#a[@]}
2

回答by mklement0

If you indeed want to write a function, you can take advantage of normal parameter parsing and the fact that $#contains the number of parameters passed:

如果你确实想写一个函数,你可以利用正常的参数解析和$#包含传递的参数数量的事实:

 foo() { echo $#; }