简体   繁体   中英

Bash - Creating a string with a string variable

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!

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.

You must surround the variable name with ${} in order to isolate it from other valid characters. Like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM