字符串格式:
字符串是shell编程中最常用最有用的数据类型,字符串可以用单引号,也可以用双引号,也可以不用引号。
str1=this is a string
str2='this is a string'
str3="this is a string"
- 单双引号的区别跟PHP类似:单引号原样输出,双引号里可以有变量。
- 不用引号和单引号字串中不能出现单独一个的单引号(对单引号使用转义符后也不行),但可成对出现,作为字符串拼接使用。
注意:
#!/bin/bash
your_name=world
str='hello, '$your_name' !'
echo str
输出结果为:hello, world!
单引号成对出现,被当成字符串拼接。
常用字符串处理
获取字符串长度
string="abcd"
echo ${#string}
#输出 4
截取字符串
string="hello world"
echo ${string:1:4}
# 输出 ello
查找字符串
查找字符 i 或 o 的位置(哪个字母先出现就计算哪个):
string="runoob is a great site"
echo `expr index "$string" io`
# 输出 4
注意: 以上脚本中 ` 是反引号,而不是单引号 ',不要看错了哦。