2

In Python, if I have a to create a string with date as suffix, we can do some thing like this:

date = get_todays_date()
name = "automation_results_{}'.format(date)

What is the equivalent of .format in shell/bash scripting language?

Benjamin
  • 2,229
  • 1
  • 13
  • 22
Vineel
  • 1,486
  • 5
  • 23
  • 42

1 Answers1

1

In bash you can get a date string by invoking date:

name="automation_results_"$(date +%Y_%m_%d) 

with the different options for the format string you can get any date format you prefer.

As @cdarke commented, if you have a recent version of bash you can also do the faster:

name=$(printf "automation_results_%(%Y_%m_%d)T")
Anthon
  • 59,987
  • 25
  • 170
  • 228
  • Since the question is about string formatting, rather than use an inefficient external program (`date`), would it not have been better to show `printf -v` with the `%(%+)T`? – cdarke Sep 09 '16 at 06:45
  • @cdarke if efficiency is required then using bash is the first thing that should be reevaluated. I tend to prefer using the more generic `$(...)` than having to remember that `printf` supports a special case for formatting dates, but that is certainly an option. OK if I update the answer with that als an alternative? – Anthon Sep 09 '16 at 07:53
  • I agree with your sentiment about efficiency and bash in general. In tests I timed that `printf` is about 100 times faster than the `date` program. If you use the `printf` alternative then you should mention that it is only available from bash version 4 (many are still on 3.2). – cdarke Sep 09 '16 at 12:48