字符串是shell编程中最常用最有用的数据类型(除了数字和字符串,也没啥其它类型好用了),字符串可以用单引号,也可以用双引号,也可以不用引号。
str=‘I am uniquefu‘
单引号字符串的限制:
name="http://www.cnblogs.com/uniquefu"
str="Hello, I know you are \"$name\"! \n"
echo ${str}
输出结果:
[root@test3101-3 bin]# ./test.sh Hello, I know you are "http://www.cnblogs.com/uniquefu"! \n
双引号的优点:
your_name="uniquefu"
# 使用双引号拼接
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
运行结果
[root@test3101-3 bin]# ./test.sh
hello, uniquefu ! hello, uniquefu !
hello, uniquefu ! hello, ${your_name} !
your_name="uniquefu"
echo ${#your_name}
输出结果:
[root@test3101-3 bin]# ./test.sh 8
以下实例从字符串第 3 个字符开始截取 5 个字符
your_name="uniquefu"
echo ${your_name:2:5}
输出结果:
[root@test3101-3 bin]# ./test.sh iquef
查找字符 i 或 f 的位置(哪个字母先出现就计算哪个):
your_name="uniquefu" echo `expr index "$your_name" if` # 输出 3
注意: 以上脚本中 ` 是反引号,而不是单引号 ‘,不要看错了哦
原文:https://www.cnblogs.com/uniquefu/p/9552885.html