Search code examples
bashvariablesdatetimeauto-update

linux bash script: set date/time variable to auto-update (for inclusion in file names)


Essentially, I have a standard format for file naming conventions. It breaks down to this:

target_dateUTC_timeUTC_tool

So, for instance, if I run tcpdump on a target of 'foo', then the file would be foo_dateUTC_timeUTC_tcpdump. Simple enough, but a pain for everyone to constantly (and consistently) enter... so I've tried to create a bash script which sets system variables like so:

FILENAME=$TARGET\_$UTCTIME\_$TOOL

Then, I can just call the variable at runtime, like so:

tcpdump -w $FILENAME.lpc

All of this works like a champ. I've got a menu-driven .sh which gives the user the options of viewing the current variables as well as setting them... file generation is a breeze. Unfortunately, by setting the date/time variable, it is locked to the value at the time of creation (naturally). I set the variable like so:

UTCTIME=$(/bin/date --utc +"%Y%m%d_%H%M%Z")

What I really need is either a way to create a variable which updates at runtime, or (more likely) another way to skin this cat.

While scouring for solutions, I came across a similar issues... like this.

But, to be honest, I'm stumped on how to marry the two approaches and create a simple, distributable solution.

.sh file is posted via pastebin, here.


Solution

  • Use a function:

    generate_filename() { echo "${1}_$(/bin/date --utc +"%Y%m%d_%H%M%Z")_$2"; }
    

    And use it like this:

    tcpdump -w "$(generate_filename foo tcpdump).lpc"
    

    It's hard to get the function to automatically determine the command name. You can use bash history to get it and save a couple of characters typing:

    tcpdump -w "$(generate_filename foo !#:0).lpc"