3

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!

3
  • 6
    The first version tries to use the CURRENTDATE_ variable. Use ${CURRENTDATE}_. The second version does exactly what you'd expect which is expand your variables and leave the single quotes intact. Commented Nov 12, 2015 at 18:50
  • As Etan pointed out, the variable name it's first expanding has an underscore appended to it. You can use his suggestion or use \ like so echo abc_$CURRENT_DATE\_$CURRENT_DATE I've also found this unix.stackexchange.com/questions/88452/… -- it's worth a read. Commented Nov 12, 2015 at 19:20
  • You can even split with quotes. echo "abc_$CURRENTDATE""_$CURRENTDATE". That said, I use curly braces almost whenever possible, to reduce unknowns. I also prefer printf. printf 'abc_%s_%s\n' "$CURRENTDATE" "$CURRENTDATE" Commented Nov 12, 2015 at 19:25

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.