Wednesday, July 11, 2012

Daily tmp directory

My $HOME/tmp directory got a bit messy, especially with building test rpms or testing tarballs. My solution was to just change the directory to automatically change daily. Scripts below:
:: whot@yabbi:~> cat scripts/tmp-today 
#!/bin/bash
date=`date +%Y-%m-%d-%a`

tmpdir=$HOME/tmp/$date
tmplink=$HOME/tmp/today

if [ -e "$tmpdir" ]; then
    exit 0
fi

mkdir $tmpdir
ln -sf $tmpdir $tmplink
And the crontab entries to run this script:
0 2 * * * /home/whot/scripts/tmp-today
@reboot /home/whot/scripts/tmp-today
So run the thing at 2.00 am and on every reboot in case the box was shut off overnight. I had it on midnight first, but I think 2 am is better. If I'm still up at 2 and working, then mentally I'm still in on the day before and I don't want files to end up in different directories just because midnight clocked over. And because the laptop may be suspended overnight, we run the script on resume as well:
:: whot@yabbi:~> cat /etc/pm/sleep.d/00-tmp-dir 
#!/bin/bash

case "$1" in
 thaw|resume)
  su -c - whot /home/whot/scripts/tmp-today
  ;;
 *)
  ;;
esac
This obviously works for other directories as well, e.g. your daily download directory.

2 comments:

skvidal said...

If you use the polyinstantion namespace feature in pam_namespace - you should be able to have your system automatically do this tmpdir creation for you.

Daniel Erat said...

Here's a similar solution that I've been using for a few years (placed in my .zshrc file). Type 't' to jump to today's temp directory, 'tp' to print the directory (useful for redirecting logs), and e.g. 't 2' to jump to the directory from the day before yesterday.

(Blogger is going to butcher the indenting.)

# Switch to temporary directories.
temp_dir() {
local base=$1
local gothere=$2
local worldreadable=$3
local create=1
if test "$4"; then
if echo "$4" | egrep -q '^[0-9]+$' && test $4 -gt 0; then
local dir=$base/$(date -d "$4 days ago" +%Y%m%d)
local create=0
else
local dir="$base/$4"
fi
else
local dir=$base/$(date +%Y%m%d)
fi

if [[ $create == 1 ]] && test \! -e "$dir"; then
mkdir -p "$dir"
if [[ $worldreadable == 1 ]]; then
chmod 755 "$dir"
fi
fi

if [[ $gothere == 1 ]]; then
cd $dir
else
echo $dir
fi
}
t() { temp_dir $HOME/temp 1 0 $1; }
tp() { temp_dir $HOME/temp 0 0 $1; }