# 计算字符串长度(字符数量)

在很多时候，我们需要知道字符串的长度(计算多少个字符)，有以下一些方法

* `wc -m` 可以计算字符串的字符数量:

```bash
STRLENGTH=$(echo -n $STRING | wc -m)
# 或者
STRLENGTH=`echo -n $STRING | wc -m`
```

不过，需要注意，这里 `wc -m` 获得的结果，会出现一个多个空格之后的数字，例如 `5`

所以还需要做一个截取

* 更好的方式是变量

```bash
myvar="This is a test"
echo "${#myvar}"
14
```

或者

```bash
expr length "${myvar}"
14
```

## 参考

* [How to find length of string in shell](https://superuser.com/questions/807573/how-to-find-length-of-string-in-shell)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://huataihuang.gitbook.io/cloud-atlas-draft/develop/shell/bash/count_string_length.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
