How to concat variable and string in bash script

强颜欢笑 提交于 2020-03-13 05:21:40

问题


How to concat variable and string in bash script ?

val1 = Variable1 + "any string "

eg :

val1 = $i + "-i-*"

where i = 24thMarch

I want echo val1 :

24thMarch-i-*

What is proper proper to get the solution ?


回答1:


Strings are concatenated by default in the 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.




回答2:


Late for the party, my 2 cents for another solu., also works in zsh:

i=`date +%d%b`

val1="$i-i-*"




回答3:


Nice.

Mac OS X 10.12 works with following ...


#!/bin/bash

var1=bar
var2=foo
var3="$var1"sometext
echo $var3

Result

= barfoosometext



来源:https://stackoverflow.com/questions/32696871/how-to-concat-variable-and-string-in-bash-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!