在几乎所有编程语言中,字符串连接都是一个很重要的组成部分。
concat_string="$str1$str2"
字符串变量拼接
$ w='Welcome'
$ printf "$w\n"Welcome
$ t='To'$ l='Linux'$ h='Handbook!'
$ tony="${w} ${t} ${l} ${h}"
通过这种方式,我将所有四个字符串连接到一个变量中,并将其命名为 tony。请注意,我在变量之间添加了一个空格。
$ printf "$tony\n"Welcome To Linux Handbook!
#!/bin/bashw='Welcome't='To'l='Linux'h='Handbook'tony="${w} ${t} ${l} ${h}"printf "${tony}\n"
$ chmod +x concat.sh$ ./concat.shWelcome To Linux Handbook!
在进行字符串拼接时,包裹变量名的花括号 {} 不是必需的。不过为了让代码更易读,最好加上花括号 {}。
字符串追加
上面的例子是将多个字符串拼接为一个。那怎样将一串字符追加到某个已存在的字符串中呢?可以使用 += 运算符来实现。如下所示:
str="iron"str+="man"
$ str="iron"$ str+="man"$ echo $strironman
#!/bin/bashvar=""for color in 'Black' 'White' 'Brown' 'Yellow'; dovar+="${color} "doneecho "$var"
Black White Brown Yellow
连接数字和字符串
正如我们前文提到的,Bash 中没有数据类型。字符串和整数是相同的,因此它们可以很容易地连接到一个字符串中。
#!/bin/bashwe='We'lv='Love'y='You'morgan=3000stark="${we} ${lv} ${y} ${morgan}!!!"printf "${stark}\n"
$ chmod +x morgan.sh$ ./morgan.shWe Love You 3000!!!
字符串的嵌套拼接
#!/bin/bashw='Welcome't='To'l='Linux'h='Handbook'tony="${w} ${t} ${l} ${h}"we='We'lv='Love'y='You'morgan=3000stark="${we} ${lv} ${y} ${morgan}!!!"ironman="${tony}..${stark}"printf "${ironman} Forever!\n"
下面是执行结果:
Welcome To Linux Handbook..We Love You 3000!!! Forever!
文章转载自TIAP,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。




