Quite often, we run an executable that needs to write / read some temporary files. We usually create a temporary directory, run the executable there, and delete the directory when the script is done.
I want to delete the directory even if the executable is killed. I tried to wrap it in:
#!/bin/bash dir=$(mktemp -d /tmp/foo.XXXXXXX) && cd $dir && rm -rf $dir /usr/local/bin/my_binary
my_binary dies, the last process the kernel will delete the directory, as the script is the last process holding that
inode; but I can't create any file in the deleted directory.
#!/bin/bash dir=$(mktemp -d /tmp/foo.XXXXXXX) && cd $dir && rm -rf $dir touch file.txt
touch: file.txt: No such file or directory
The best I could come up with is to delete the temp directory when the process dies, catching the most common signals, and run a cleanup process with cron:
#!/bin/bash dir=$(mktemp -d /tmp/d.XXXXXX) && cd "$dir" || exit 99 trap 'rm -rf "$dir"' EXIT /usr/local/bin/my_binary
Is there some simple way to create a really temporary directory that gets deleted automatically when the current binary dies, no matter what?