bash variable interpolation separate variables by a hyphen or underscore

Solution 1:

By telling bash where the variable name ends.

"${filename}_$yesterday.CSV"

Solution 2:

Several possibilities:

  • The most natural one: enclose your variable name in curly brackets (Ignacio Vazquez-Abrams's solution):

    echo "${filename}_$yesterday.CSV"
    
  • Since your separator is a rather special character, you may use a backslash (Sriharsha's Kallury's solution):

    echo "$filename\_$yesterday.CSV"
    
  • (Ab)use quotes:

    echo "$filename""_$yesterday.CSV"
    

    or

    echo "$filename"_"$yesterday.CSV"
    
  • Use an auxiliary variable for the separator:

    sep=_
    echo "$filename$sep$yesterday.CSV"
    
  • Use an auxiliary variable for the final string, and build it step by step:

    final=$filename
    final+=_$yesterday.CSV
    echo "$final"
    

    or in a longer fashion:

    final=$filename
    final+=_
    final+=$yesterday
    final+=.CSV
    echo "$final"
    
  • Use an auxiliary variable for the final string, and build it with printf:

    printf -v final "%s_%s.CSV" "$filename" "$yesterday"
    echo "$final"
    

(feel free to add other methods to this post).