4

As I've been learning more about Ubuntu and bash programming I've been storing variables in /tmp. For example in-between calls to the same bash script I want to record the previous state.

On my current single user system there is no danger of conflicts in /tmp directory. However I want my code to be future-proof and wonder if I should get in the habit of using a directory called ~/tmp?

Perhaps it should be ~/.tmp and hidden. Perhaps it should be ~/temp so as not to be confused with conventional /tmp directory.

Any ideas / suggestions are appreciated. Thank you.

WinEunuuchs2Unix
  • 99,709
  • 34
  • 237
  • 401
  • I prefer to use `/tmp` but name the files with some randomness attached to the filename. `head /dev/urandom | tr -dc A-Za-z0-9 | head -c 13 ; echo ''` I'm sure this has it's own set of caveats. –  Feb 12 '17 at 17:00
  • I'm using fixed names hard coded in the script. ie `/tmp/lock-screen-timer-remaining` which contains a single line with "30 minutes", "29 minutes" ... – WinEunuuchs2Unix Feb 12 '17 at 17:08
  • At a minimum, you could use `$$`variable in `bash` script as part of the file, as your process ID should be unique in a running system. Or create a user directory in `/tmp`. The advantage of `/tmp`directory is that it is emptied at reboot when properly configured. – ridgy Feb 12 '17 at 17:58
  • @ridgy The process ID will change each time the script is called. Other scripts reading the status needs a static file name to open. I like your idea of creating a user directory within `/tmp` do you know if it's common practice? – WinEunuuchs2Unix Feb 12 '17 at 18:11
  • Assuming we talk about some current Ubuntu, just have a look at /tmp (`ls -l /tmp`), to see what applications do (all directories owned by you are created for you, and some will have your username in the directory name...) – ridgy Feb 12 '17 at 18:20

1 Answers1

1

Generally if you wish to store the state for each user the easiest way is to just create a dedicated directory for the application in the users home directory:

CFGDIR="${HOME}/.mycoolapp"
mkdir -p ${CFGDIR}
# read / write files in ${CFGDIR} here..

If you just want a temporary storage for one instance of the script, a good approach is to use mktemp. For example:

TMPDIR="$(mktemp -d)"
# read / write files in ${TMPDIR} here..
rm -rf ${TMPDIR}
d99kris
  • 366
  • 3
  • 8