bash variable interpolation separate variables by a hyphen or underscore

后端 未结 3 1309
死守一世寂寞
死守一世寂寞 2020-11-30 15:30

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 commen

相关标签:
3条回答
  • 2020-11-30 15:42

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

    0 讨论(0)
  • 2020-11-30 15:46

    By telling bash where the variable name ends.

    "${filename}_$yesterday.CSV"
    
    0 讨论(0)
  • 2020-11-30 15:59

    You can use backslash to do that.

    # filename=test
    # yesterday=somedate
    # echo $filename_$yesterday.csv
    somedate.csv
    # echo $filename\_$yesterday.csv
    test_somedate.csv
    #
    
    0 讨论(0)
提交回复
热议问题