• Uncategorized

About bash : bash-variable-interpolation-separate-variables-by-a-hyphen-or-underscore

Question Detail

This is a simple script just to see if the file has been downloaded. On this script the find command always evaluated to zero – even if it didn’t find anything. So I commented it out.

on the filename="day_CTRwFEES_hoo01M_" I had to add an underscore to the end of the filename.

Using an underscore $filename_$yesterday.CSV to separate the two did not work. – I had to take out the underscore, add it to the filename and then combine the variables to make it work like this – $filename$yesterday.

How could I get it to work without adding the underscore to the end of the variable $filename?

set -x
dayofweek=$(/bin/date +%w)
today=$(/bin/date +%Y%m%d)
yesterday=$(/bin/date -d "1 day ago" +%Y%m%d)
friday_morning=$(/bin/date -d "3 days ago" +%Y%m%d)

#if find /data/today/ -type f -name "$filename_$yesterday.CSV" ; then
if ls "/data/today/$filename$yesterday.CSV" ; then
    echo "successful"
    echo "$filename$yesterday.CSV was not downloaded, please check." | mail -s "$filename$yesterday.CSV not downloaded" [email protected]_bank.com

[email protected]_host5981dap:~/walt/morning_checks$ ./check_day_CTRwFEES_hoo01M
++ /bin/date +%w
+ dayofweek=5
++ /bin/date +%Y%m%d
+ today=20141024
++ /bin/date -d '1 day ago' +%Y%m%d
+ yesterday=20141023
++ /bin/date -d '3 days ago' +%Y%m%d
+ friday_morning=20141021
+ filename=day_CTRwFEES_hoo01M_
+ ls data/today/day_CTRwFEES_hoo01M_20141023.CSV
+ echo successful


Question Answer

By telling bash where the variable name ends.


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"


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

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

    echo "$final"

    or in a longer fashion:

    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).

You can use backslash to do that.

# filename=test
# yesterday=somedate
# echo $filename_$yesterday.csv
# echo $filename\_$yesterday.csv

You may also like...

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.