Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to concat variable and string in bash script

Tags:

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 ?

like image 423
Ashish Karpe Avatar asked Sep 21 '15 13:09

Ashish Karpe


People also ask

How do you combine variables and strings?

In JavaScript, we can assign strings to a variable and use concatenation to combine the variable to another string. To concatenate a string, you add a plus sign+ between the strings or string variables you want to connect. let myPet = 'seahorse'; console.

How do I append a string to a string in bash?

Bash also allows string concatenation using the += operator. Simply a+=b can be understood as a=a+b . Here, STR2 is appended at the end of STR1 , and the result is stored in the STR1 variable. To append multiple values, we can use a simple for loop.

How do you concatenate in a Unix script?

String concatenation is the process of appending a string to the end of another string. This can be done with shell scripting using two methods: using the += operator, or simply writing strings one after the other.

Can we concat string and int?

To concatenate a string to an int value, use the concatenation operator. Here is our int. int val = 3; Now, to concatenate a string, you need to declare a string and use the + operator.


2 Answers

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.

like image 103
Tom Fenech Avatar answered Nov 01 '22 06:11

Tom Fenech


Nice.

Mac OS X 10.12 works with following ...


#!/bin/bash  var1=bar var2=foo var3="$var1"sometext echo $var3 

Result

= barfoosometext

like image 32
paulgass Avatar answered Nov 01 '22 06:11

paulgass