2.shell教程之字符串

shell教程之字符串

字符串

字符串可以使用单引号和双引号,也可以不使用引号

单引号

str='this is a string'

单引号字符串的限制

  • 单引号的任何字符都会原样输出,单引号字符串中的变量是无效的
  • 单引号字符串中不能出现单独一个的单引号

双引号

name='zlb'
str="hello,I know you are ${name} ! \n"
echo -e ${str}
hello,I know you are zlb ! 

双引号的优点:

  • 双引号里可以有变量
  • 双引号里可以出现转义字符

拼接字符串

name="zlb"
# 使用双引号拼接
greeting="hello,"${name}" !"
greeting_1="hello,${name} !"
echo ${greeting} $greeting_1
# 使用单引号拼接
greeting_2='hello,'${name}' !'
greeting_3='hello,${name} !'
echo $greeting_2 $greeting_3
hello,zlb ! hello,zlb !
hello,zlb ! hello,${name} !

获取字符串的长度

string='abcd'
echo ${#string}

4

提取字符串

string='runoob is a great site'
echo ${string:1:4}

unoo

查找子字符串

查找i或者o的位置

string='runoob is a great site'
echo `expr index "${string}" io`

⚠️`为反引号,而不是单引号’

posted @ 2020-09-28 20:18  zlbingo  阅读(44)  评论(0)    收藏  举报