Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash - Creating a string with a string variable

Tags:

string

linux

bash

I have a variable called CURRENTDATE=20151105.

I want to create a string as below:

abc_20151105_20151105

I tried the following variations:

echo "abc_$CURRENTDATE_$CURRENTDATE" 
This gave abc_20151105

echo "abc_'$CURRENTDATE'_'$CURRENTDATE'"
This gave abc_'20151105'_'20151105'

What am I missing here? Thanks in advance!

like image 378
activelearner Avatar asked Dec 28 '25 19:12

activelearner


1 Answers

The problem is that the underscore is a valid character for a variable name. Try one of these:

echo "abc_"$CURRENT_DATE"_"$CURRENT_DATE
echo "abc_${CURRENT_DATE}_$CURRENT_DATE"

Bash doesn't have a concatenation operator, so you concatenate strings by smashing them together in the command; this is what the first example is doing. The second uses braces to explicitly point out the variable name.

like image 176
miken32 Avatar answered Dec 30 '25 08:12

miken32



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!