bash 如何在bash脚本中连接变量和字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32696871/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to concat variable and string in bash script
提问by Ashish Karpe
How to concat variable and string in bash script ?
如何在 bash 脚本中连接变量和字符串?
val1 = Variable1 + "any string "
eg :
例如:
val1 = $i + "-i-*"
where i = 24thMarch
其中 i = 3 月 24 日
I want echo val1 :
我想要回声 val1 :
24thMarch-i-*
What is proper proper to get the solution ?
获得解决方案的正确方法是什么?
回答by Tom Fenech
Strings are concatenated by default in the shell.
默认情况下,字符串在 shell 中连接在一起。
value="$variable"text"$other_variable"
It's generally considered good practice to wrap variable expansions in double quotes.
通常认为将变量扩展用双引号括起来是一种很好的做法。
You can also do this:
你也可以这样做:
value="${variable}text${other_variable}"
The curly braces are useful when dealing with a mixture of variable names and strings.
花括号在处理变量名和字符串的混合时很有用。
Note that there should be no spaces around the =
in an assignment.
请注意,=
作业中的周围不应有空格。
回答by Timo
Late for the party, my 2 cents for another solu., also works in zsh
:
聚会迟到了,我的另一个解决方案 2 美分,也适用于zsh
:
i=`date +%d%b`
val1="$i-i-*"
val1="$i-i-*"
回答by paulgass
Nice.
好的。
Mac OS X 10.12 works with following ...
Mac OS X 10.12 适用于以下...
#!/bin/bash
var1=bar
var2=foo
var3="$var1"sometext
echo $var3
Result
结果
= barfoosometext
= barfoosometext