# 4.Shell 字符串

> ## Shell 字符串 <a href="#san-shell-zi-fu-chuan" id="san-shell-zi-fu-chuan"></a>

字符串是shell编程中最常用最有用的数据类型（除了数字和字符串，也没啥其它类型好用了），字符串可以用单引号，也可以用双引号，也可以不用引号。单双引号的区别跟PHP类似。

> ### 单引号 <a href="#dan-yin-hao" id="dan-yin-hao"></a>

```
1.str='this is a string'
```

> **单引号字符串的限制：**
>
> * 单引号里&#x7684;**`任何字符都会原样输出，单引号字符串中的变量是无效`**&#x7684;；
> * 单引号字串中不能出现单引号（对单引号使用转义符后也不行）。

> ### 双引号 <a href="#shuang-yin-hao" id="shuang-yin-hao"></a>

```
1.your_name='qinjx'
2.str="Hello, I know your are \"$your_name\"! \n"
```

> 双引号的优点：
>
> * 双引号里可以有变量
> * 双引号里可以出现转义字符

> ### 拼接字符串 <a href="#pin-jie-zi-fu-chuan" id="pin-jie-zi-fu-chuan"></a>

```
1.your_name="qinjx"
2.greeting="hello, "$your_name" !"
3.greeting_1="hello, ${your_name} !"
4.echo $greeting $greeting_1
```

> ### 获取字符串长度 <a href="#huo-qu-zi-fu-chuan-chang-du" id="huo-qu-zi-fu-chuan-chang-du"></a>

```
1.string="abcd"
2.echo ${#string} #输出 4
```

**实践**

```
1.#!/bin/bash
2.
3.your_name="onetwothree"
4.
5.echo $(#your_name)
```

输出结果

```
1.[root@localhost lcr]# ./helloworld.sh 
2../helloworld.sh:行5: 寻找匹配的 `)' 是遇到了未预期的文件结束符
3../helloworld.sh:行8: 语法错误: 未预期的文件结尾
```

**括号不对**

> ### 提取子字符串 <a href="#ti-qu-zi-zi-fu-chuan" id="ti-qu-zi-zi-fu-chuan"></a>

以下实例从字符串第 2 个字符开始截取 4 个字符：

```
1.string="runoob is a great site"
2.echo ${string:1:4} # 输出 unoo
```

**实践**

```
1.#!/bin/bash
2.
3.your_name="runoob is a great site"
4.echo ${your_name:5:11}
```

输出结果

```
1.b is a grea
2.[root@localhost lcr]# ./helloworld.sh 
3.b is a grea
```

> ### 查找子字符串 <a href="#cha-zhao-zi-zi-fu-chuan" id="cha-zhao-zi-zi-fu-chuan"></a>

查找字符 “i 或 s” 的位置：

```
1.string="runoob is a great company"
2.echo `expr index "$string" is`  # 输出 8
```

**注意：** 以上脚本中 “\`” 是**反引号**，而不是单引号 “’”，不要看错了哦。\
**实践**

```
1.#!/bin/bash
2.
3.string="LCR is not loser"
4.
5.echo `expr index "$string" is`
```


---

# 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://toska.gitbook.io/sysadmin/shell-and-bash/4.shell-zi-fu-chuan.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.
