1

I googled and googled, and nowhere could I find any help or related posts to my question...

How do I specify a file that has just been timestamped within a bash script? Thank you very much for your time.

Basic Example:

  #!/bin/sh
  touch $(date +'%Y-%m-%d_%H-%M-%S').log
  program --start --output /home/user/.logs/the_above_timestamped_file.log

Precise Example:

The below code is a non-working bash script, no success of the program writing to the timestamped log file, or the program can't find the timestamped log file? Or perhaps it doesn't know which file to write to since the timestamped file is one of many within the directory of logs. Wish I knew how to figure this out...

  #!/bin/sh
  # start the logkeys service
  # create a timestamped file
  # append key logging to that file

  LOG_FILE_NAME=$(date +'%Y-%m-%d_%H-%M-%S')_key.log
  touch "/mnt/WDRED6TBHDD/text/keylog/$LOG_FILE_NAME"
  sudo logkeys --start --output "/mnt/WDRED6TBHDD/text/keylog/$LOG_FILE_NAME"
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Anonymous
  • 131
  • 5

1 Answers1

2

Create a variable with the date string and reuse it.

#!/bin/sh
DATE_STR=$(date +'%Y-%m-%d_%H-%M-%S')
touch "$DATE_STR.log"
program --start --output "/home/user/.logs/$DATE_STR.log"

Or the entire file name.

#!/bin/sh
LOG_FILE_NAME=$(date +'%Y-%m-%d_%H-%M-%S').log
touch "$LOG_FILE_NAME"
program --start --output "/home/user/.logs/$LOG_FILE_NAME"
virullius
  • 939
  • 6
  • 17
  • 1
    Get into the habit of quoting your variable names ([Security implications of forgetting to quote a variable in bash/POSIX shells](https://unix.stackexchange.com/questions/171346/security-implications-of-forgetting-to-quote-a-variable-in-bash-posix-shells)), and get out of the habit of using ALLCAPS vars ([“ls: not found” after running “read PATH”](https://stackoverflow.com/questions/28310594/ls-not-found-after-running-read-path)) – glenn jackman Aug 23 '18 at 19:22
  • Definitely quote variable names. Thanks for the reminder @glennjackman, I was a bit hasty in typing the answer. – virullius Aug 23 '18 at 19:23
  • Hey I tried both of your methods of bash code and neither worked for me. I am running Linux Manjaro 17.1.7. I am originally trying to run the "logkeys" program so you can replace "program" with "logkeys" to test if you want. Any ideas why this is not working? All it did was create the timestamped file within my home directory with nothing written to it by logkeys. However if you "touch test.log and then "logkeys --start --output test.log" it works great. Not sure why this is not working though? I have updated my post with my current code that doesn't seem to work. Thanks so much for your time. – Anonymous Aug 24 '18 at 22:59
  • I don't see anything obvious, try adding `set -x` to the script to trace the commands it's running to confirm they look correct. – virullius Aug 25 '18 at 14:57