Paul Kaplan
Paul Kaplan

Reputation: 2885

bash create file based on date?

I'm trying to write a bash script to create/check for the existence of a file based on the date. Basically I want to have a direcotry of todo_lists inside of which are files with todays todo list. So every time I open the terminal (mac os 10.6.8) it would check to see if 6-29-11.txt or whatever based on

date "+%m%d%Y"

if it exists just less the contents of it and if it doesn't create one.

so I was wondering how to use that date formatted string as a file name and how to check string variables i.e.

[ -e date_string.txt ] && ...

How would I accomplish these things, I'm pretty new to bash

Upvotes: 2

Views: 2864

Answers (2)

clt60
clt60

Reputation: 63952

For this purpose your Mac has bullets already inserted.

In short: you can make any file (default is $HOME/calendar) and you can enter one line reminder into it in the form like:

06/29<TAB>reminder for today
06/30<TAB>reminder for tomorrow
07/15<TAB>another one

and into your $HOME/.profile simple enter the calendar command.

After the above, every time you open a new terminal window, the calendar command will consult the calendar file for the today reminders and when found a reminder, will print out it...

you can include more different calendars (with namedays for example) and more...
check man calendar


and the answer to your qst is:

file="./todo/$(date "+%F").txt"
[ -f "$file" ] && {
        echo "My today reminders"
        cat "$file"
}

I suggest use the format "+%F" (2011-06-29) because you get a sorted list of files, when you do ls or so...

ps: use $(command ....) form instead of `command` (backticks) because you can easily nest $(command $(another $(nexT))) them. Backticks are deprecated in the current bash.

Upvotes: 2

Geoffrey
Geoffrey

Reputation: 11354

Try this:

DATE=`date "+%m%d%Y"`
if [ -f "todo_lists/$DATE.txt" ]; then
  do stuff
fi

The backticks (`) means, run this command and return the output as a string

Upvotes: 5

Related Questions