如何在bash中的变量中存储字符串的长度? [英] How to store the length of a string in a variable in bash?

查看:151
本文介绍了如何在bash中的变量中存储字符串的长度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用此指南作为参考.

I am using this guide as a reference.

我能够运行命令来查找字符串的长度,例如

I am able to run the command to find the length of a string, say

expr length 'monkey brains'

将按预期返回13

但是我在将结果存储到变量中遇到麻烦,比如说一个叫hi的变量.首先,我尝试直接分配嗨

However I am having trouble with storing the result in a variable, say a variable called hi. First I tried straight up assigning hi

hi=expr length 'monkey brains'

给出未找到命令的错误. 然后,我的想法是将命令全部包装在一个字符串中,然后使用

which gave a command not found error. My thought process was then to wrap the command all in a string and then use $ to evaluate the string. So what I have is

hi="expr length 'monkey brains'"
echo $($hi)

但是这也不起作用-expr:语法错误

but this didn't work either - expr: syntax error

有人知道我可以在这里尝试什么还是为什么我的方法行不通?

Does anyone know what else I could try here or why my approach doesn't work?

推荐答案

我认为这就是您要尝试的方法.

I think this is what you're trying to do.

$ expr length 'monkey brains'
13

要使用命令替换将输出存储到变量中:

To store the output to a variable using command substitution:

$ len=$(expr length 'monkey brains'); echo "$len"
13

您还可以在bash中使用参数扩展来做到这一点:

You can also do this using parameter expansion in bash:

$ string='monkey brains'; len=${#string}; echo "$len"
13

Bash Hackers Wiki

Both the Bash Hackers Wiki and the Bash Guide are good resources for information.

这篇关于如何在bash中的变量中存储字符串的长度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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