0

I need to write a shell script to redirect output of a java program to a log file which I can do by

java abc > logfile.log

However, I need to create logfile.log with the current date appended, ensuring that only one such file is created for a day, otherwise the output is appended to the existing file with the current date.

How can this be done in the shell script?

S_S
  • 1,276
  • 4
  • 24
  • 47
  • you can use following "logfile_$(date +%F).log" this will let you create file with current date. – mohammed Oct 15 '19 at 08:02
  • Possible duplicate of [Append date to filename in linux](https://stackoverflow.com/q/1795678/608639), [Appending a current date from a variable to a filename](https://unix.stackexchange.com/q/57590), [Adding timestamp to a filename with mv in BASH](https://stackoverflow.com/q/8228047/608639), [Creating filename_$(date %Y-%m-%d) from systemd bash inline script](https://stackoverflow.com/q/45999187/608639), [Bash alias create file with current timestamp in filename](https://stackoverflow.com/q/24236362), [Creating tar file and naming by current date](https://stackoverflow.com/q/18498359), etc. – jww Oct 15 '19 at 08:21
  • @jww Can you share how to locate "possible duplicates" (or just similar questions) efficiently ? I'm trying to learn how to be more effective with SO. – dash-o Oct 15 '19 at 12:34

1 Answers1

3

You can use date to choose the format of the log file. Assuming YYYY-MM-DD, you can use the following. Note using '>>' to append/create the log file.

java abc.java >> "logfile.$(date +'%Y-%m-%d').log"
# Test
echo abc.java >> "logfile.$(date +'%Y-%m-%d').log"

Also note that 'java abc.java' need to be reviewed. The java command is usually invoked with class name (java abc), and not the name of a file.

dash-o
  • 13,723
  • 1
  • 10
  • 37