如何在bash脚本中连接字符串?


21

如何在shell脚本中连接字符串和变量?

stringOne =“foo”

stringTwo =“anythingButBar”

stringThree =“?和?”

我想输出“foo和anythingButBar”

Answers:


29

没什么特别的,你只需要将它们添加到你的声明中。

例如:

[Zypher@host01 monitor]$ stringOne="foo"
[Zypher@host01 monitor]$ stringTwo="anythingButBar"
[Zypher@host01 monitor]$ stringThree=$stringOne$stringTwo
[Zypher@host01 monitor]$ echo $stringThree 
fooanythingButBar

如果你想要它们之间的文字'和':

[Zypher@host01 monitor]$ stringOne="foo"
[Zypher@host01 monitor]$ stringTwo="anythingButBar"
[Zypher@host01 monitor]$ stringThree="$stringOne and $stringTwo"
[Zypher@host01 monitor]$ echo $stringThree 
foo and anythingButBar

4
如果我可以提出建议,你的提示是嘈杂的,并且模糊了你的答案(美元符号之后的空格有助于提高可读性)。就像是 $ stringOne="foo", 例如。此外,提示不应出现在输出行(回声之后的行)上。否则+1。
Dennis Williamson

9
echo ${stringOne}and${stringTwo} 如果你不想要空格
max taldykin

你也可以 stringThree=$stringOne" and "$stringTwo
Armfoot

5

相反,你有:

stringOne="foo"
stringTwo="anythingButBar"
stringThree="%s and %s"

你可以这样做:

$ printf "$stringThree\n" "$stringOne" "$stringTwo"
foo and anythingButBar
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.