Shell 字符串
本文最后更新于:2024年3月18日 凌晨
Shell 字符串
- 字符串可以用单引号,也可以用双引号,也可以不用引号。
单引号
单引号字符串的限制:
- 单引号里的任何字符都会原样输出,单引号字符串中的变量是无效的。
- 单引号字串中不能出现单独一个的单引号(对单引号使用转义符后也不行),但可成对出现,作为字符串拼接使用。
双引号
1 2 3
| your_name='test' str="Hello, I know you are \"$your_name\"! \n" echo -e $str
|
输出结果为:
1
| Hello, I know you are "test"!
|
双引号的优点:
拼接字符串
1 2 3 4 5 6 7 8 9
| your_name="test" # 使用双引号拼接 greeting="hello, "$your_name" !" greeting_1="hello, ${your_name} !" echo $greeting $greeting_1 # 使用单引号拼接 greeting_2='hello, '$your_name' !' greeting_3='hello, ${your_name} !' echo $greeting_2 $greeting_3
|
1 2
| hello, test ! hello, test ! hello, test ! hello, ${your_name} !
|
获取字符串长度
1 2
| string="abcd" echo ${#string} #输出 4
|
提取子字符串
1 2
| string="test is a great site" echo ${string:1:3} # 输出est
|
注意:第一个字符的索引值为0
查找子字符串
1 2
| string="test is a great site" echo `expr index "$string" io` # 输出 5
|