1. 60
  1.  

    1. 52

      Couldn’t agree more! I think I shared this on lobsters years ago, but my favorite thing in my ~/.zshrc is this little guy:

      function t {
        pushd $(mktemp -d /tmp/$1.XXXX)
      }
      

      If I run ‘t blah’, I’ll drop into a temporary directory with a name like /tmp/blah.1tyC. I can goof around without worrying about cleaning up the mess later. When I’m done I can popd back to where ever I was. On the off chance I like what I did, I can just move the folder somewhere permanent. I use this every day; my $HOME would be unnavigable without it.

      1. 8

        I like to automate the “popd && rm” part in the alias directly. This bash function enters a subshell inside the tmpdir and when I exit or ^D, it pops back to the previous directory and deletes the tmpdir – with a little safeguard when you mounted something inside it! Had a bad time when experimenting with mount namespaces and accidentally deleted my home directory because it was mounted inside this tmpdir …

        tmp() {
          history -w || true
          t=$(mktemp --tmpdir -d tmpdir-XXXXXX) \
            && { $SHELL -c \
             "cd '$t' \
              && printf '\033[31m%s\033[0m\n' 'this directory will be removed upon exit' \
              && pwd \
              && exec $SHELL" \
             || true; \
            } \
            && if awk '{ print $2 }' /etc/mtab | grep "$t"; then
              echo -e "\033[31maborting removal due to mounts\033[0m" >&2
            else
              echo -e "\033[31mremoving temporary directory ...\033[0m" >&2
              rm -rf "$t"
            fi
        }
        

        Here is a more recent one for fish as well.

        1. 5

          RAII, shell-style

        2. 5

          I have nearly the same function, but I’m using ~/tmp has the base, precisely because /tmp is often emptied on boot and I know that I sometimes want to go back to these experiments.

          Using ~/tmp helps keep my home directory clean and makes it obvious that the stuff is easily removable, but if, on an off-chance, I might need one of those experiments again, it’s there, waiting for me in ~/tmp even though I might have rebooted in the mean time.

          But in general, yes, this is the way to go. I’ve learned it here on lobsters years ago and I’m using it daily.

          1. 1

            I like this idea, I came to the same conclusion as you, but instead of doing ~/tmp, I added “tmp” to my personal monorepo’s .gitignore. But sometimes I would put random downloads in that folder, lol. Thanks for the idea, I feel like having two of these makes sense, one for coding stuff and one for everything else

            1. 1

              Heh, i do both:)

          2. 4

            This is absolutely fantastic. I’ve been independently using this trick for years (through ^R instead of an alias) and I love it too. I didn’t know mktemp took an argument though, thank you!

            1. 3

              I like to do programming-language-specific versions of this. So like “newrust” creates a temp dir, puts a Cargo hello world project in there, cd’s in there, and opens my editor. Similarly “newgo”, “newcpp”, etc. Great for playing around.

              1. 1

                I tend to have two use-cases for these, one that’s very very temporary (single shell instance), and one that should stick around a little longer (i.e. duration of the boot). This works out to something along the lines of

                t() {
                	mkdir -p /tmp/t
                	cd /tmp/t
                }
                tt() {
                	local dir=$(mktemp -d)
                	[ -d "$dir" ] || return 1
                	cd "$dir"
                	trap "rm -rf '$dir'" EXIT
                }
                

                Notably, I use cd because I rarely popd at the end, I usually just close the shell once I’m done with it. I probably should do it anyway though :)

                1. 1

                  Oh man, thank you so much, this is the kind of “small purpose, great impact” tools that I love! Here’s my fish version where the argument is optional.

                  function t
                      if test -z $argv[1]
                          set dirname xx
                      else
                          set dirname $argv[1]
                      end
                      pushd (mktemp -d -t $dirname.XXXX)
                  end
                  
                  1. 1

                    What kind of experiments are you doing with folders exactly? I’m curious about the overall workflow where you would like a folder’s contents or not.

                    1. 7

                      Personally I often try out small experiments with different programming languages which need a project structure to be set up before they can work properly. For this a new folder is often needed.

                      1. 2

                        For me, I just do a lot of stuff directly in /tmp, but this seems nice to keep things organized in case I want to move a directory to somewhere more permanent.

                        Scenario A: I’m trying to test something in C/Zig and don’t want to pollute my actual project directory. I just make a /tmp/test.{c, zig} and compile in /tmp. I think putting it in a temp dir would be nice, if unnecessary.

                        Scenario B: I, semi-frequently, will clone git repos into /tmp if I’m just trying to quickly look at something. Occasionally, I clone multiple related repos at the same time. Having a temp dir to keep them together would be nice if I ended up wanting to move them out.

                        1. 2

                          For me it’s poking around in exploded jar files, or tarballs, or other archive formats mostly.

                          Sometimes you don’t just want to list the contents, or maybe there are container formats in container formats, a zip inside a tar, inside a cpio for example.

                          I want to unpack all these, look around, examine files, etc. without worrying about needing to clean up the mess after.

                        2. 1

                          I have the exact same function. It’s so freakin’ useful.

                        3. 29

                          Downloads? To-do lists? Not sold. I prefer to throw things away deliberately, rather than when I just happen to reboot, which is normally quite an infrequent event.

                          1. 8

                            Agree. It’s also not just on reboot; some systems have tools that clean /tmp and other directories (e.g. tmpfiles.d, macOS has similar).

                            1. 3

                              How often do people here reboot? Since moving to the 6.8 linux kernel, I’ve started encountering regular memory leaks and begsn to restart every few days. (Battery life is great, so I stay.)

                              1. 13

                                I’m personally a big fan of daily. Switch the work computer on in the morning and off in the evening.

                                1. 4

                                  I have also been doing that basically all my life. I have no control over my browser tabs so one of the best things to keep that in check is to close everything at the end of the day (and I deliberately do not want them restored).

                                  1. 1

                                    Turning off tab restore is a controversial but smart plan. :)

                                    1. 1

                                      I can only recommend it. Over the years I feel like the browser history navigation has degraded due to keyboard highjacking and more and more links just open in a new tab (window) anyways; which makes going back work unreliably. So I just end up with loads of tabs, and I think it’s just easier to close them all at the end of the day.

                                2. 4

                                  Part of the problem is that it’s not predictable. It may be months away, it may be tomorrow. I reboot when either of the following happens:

                                  • A new OS has features I care about.
                                  • A kernel (or libc or some sufficiently low-level library that restarting everything that uses it means remastering almost everything) security vulnerability is disclosed.
                                  • The kernel crashes.

                                  Of these, only the first is something I can plan for in advance. If I create something in /tmp the it may last for months or it may go away almost instantly if there’s a crash. For downloads, going away almost instantly is probably fine, but a lot of systems make /tmp a RAM disk (tmpfs literally has it in the name!) and accumulating a few GiBs of rarely-accessed things in a RAM disk is not ideal.

                              2. 16

                                I do the opposite. My scratchpad is at ~/scratch. All folders have a format of $date-name, and about once a year I archive last year’s into ~/scratch/$year/. Learned this from a coworker a few years ago and adopted it. I’ve yet to find a reason to delete.

                                1. 1

                                  *nod* One of these days, as I’m now finally starting to get my time management and tooling in order, I’m going to go through the home_old folder where I keep the remaining bits and pieces I haven’t yet triaged from the home directory of the PC I stopped using in 2007.

                                  Maybe it’ll save me the trouble of having to go through mountains of DVD+Rs to find less easy-to-remember-the-existence-of things in the vein of “My original 1997 website, which I want to add to a git history for my current website”.

                                2. 10

                                  Relevant recent post by @fanf with Lobsters discussion: https://lobste.rs/s/esmju4/against_tmp

                                  1. 9

                                    That post also had https://systemd.io/TEMPORARY_DIRECTORIES/ merged into it which has the best advice at the top – use /tmp for small files, /var/tmp for larger files and $TMPDIR instead of either if it is set.

                                    The article here suggests using /tmp for downloads, which will work on some systems, but on other systems /tmp might be a tmpfs and you’re downloading into memory/swap.

                                  2. 8

                                    On a multi-user machine /tmp is shared. For downloads I would prefer some world-unreadable directory. Though I don’t even know what are the recommendations for things like that nowadays. On Linux there’s /run/user/<uid>, maybe this one? Does xdg have any dir for “user’s temp files”?

                                    1. 8

                                      XDG_CACHE_HOME would be the closest match.

                                      1. 1

                                        I know you’re replying to the last question of the parent comment, but, for downloads, if using XDG user directories, might as well use XDG_DOWNLOAD_DIR.

                                      2. 8

                                        On macOS $TMPDIR is a per user location unlike /tmp – although I suspect fewer macs are shared than Linux systems.

                                        1. 3

                                          This makes me curious. Do you do a lot of work like described in the article on a multi-user machine?

                                          1. 3

                                            All my home systems are configured with NixOS and have users for everyone that might need to use them, so kind of yes.

                                            But my PoV here is about doing things right w.r.t. security “and just in case”. If you have a system daemon that runs as a separate user, and it’s compromised, you don’t want it to snoop/modify your downloads etc.

                                          2. 2

                                            There’s $XDG_RUNTIME_DIR, which is usually /run/user/<uid>

                                            https://specifications.freedesktop.org/basedir-spec/latest/#basics

                                            1. 4

                                              I think that’s a bad place for downloads, since the spec says

                                              Applications should use this directory for communication and synchronization purposes and should not place larger files in it, since it might reside in runtime memory and cannot necessarily be swapped out to disk.

                                              Practically speaking, on many distros this directory is a tmpfs a few GBs or so in size, so you do actually run into the size limit, it’s not just a theoretical thing.

                                            2. 2

                                              On my client machines, I create ~/tmp/ and use that as a location to download, unzip source bundles when I only need a single file, throw a clone of a project for a comparison. I have it set up as a ram disk with a 7 day retention so it works more or less like tmp. Additionally, I set the noexec bit on the directory which makes it a better place for stuff that I just want to dig through.

                                              A huge amount of the stuff that I bring onto my box comes through the ~/tmp/ folder first, and after looking at it and deciding I need it for longer I will move things to a disk some where.

                                              I realized at some point that there’s a lot of stuff I know I’d toss in 2 hours but I also didn’t want to put it in actual tmp because it’s shared and I don’t want to mess with permissions or deleting it later.

                                            3. 6

                                              This is a terrible advice, especially coming from a security lecturer.

                                              Actually you shouldn’t really use /tmp, especially if you’re on a multi-user system. You should use your own temp directory with proper rights, so other users won’t be able to peek into your files.

                                              Also make sure you don’t ever mount anything to /tmp. Because on distributions that clear /tmp, if you forget to unmount before rebooting, your device/network share can be wiped out.

                                              1. 1

                                                on distributions that clear /tmp, if you forget to unmount before rebooting, your device/network share can be wiped out.

                                                But this happens during the boot process, not the shutdown process. So temporary mounts will not be mounted anymore. Right?

                                                1. 1

                                                  It’s nowhere that easy. It depends on the distribution if and how tmpfs is cleared. Some also use tmpwatch(8).

                                                2. 1

                                                  In what kind of enviornment people use multi-user system? Except at school, where this is not your computer so you should not store things on it anyway, i have never encountered such systems.

                                                  Assuming that almost everybody use a single-user personal computer, i don’t see how this is a “terrible advice”.

                                                  1. 1

                                                    Don’t assume other people use the machine the same way as you’re using it, especially if you give advice to others.

                                                    Some people share their stuff with their friends. Some use shared VPSes. Lots of sharing is done on work machines.

                                                3. 5

                                                  For fun, tmpfiles.d(5) supports lifetimes on arbitrary directories. This is how /tmp is cleared on a 30 day rotation if you don’t reboot your machine.

                                                  λ ~ » cat /usr/lib/tmpfiles.d/tmp.conf
                                                  #  This file is part of systemd.
                                                  #
                                                  #  systemd is free software; you can redistribute it and/or modify it
                                                  #  under the terms of the GNU Lesser General Public License as published by
                                                  #  the Free Software Foundation; either version 2.1 of the License, or
                                                  #  (at your option) any later version.
                                                  
                                                  # See tmpfiles.d(5) for details.
                                                  
                                                  # Clear tmp directories separately, to make them easier to override
                                                  q /tmp 1777 root root 10d
                                                  q /var/tmp 1777 root root 30d
                                                  

                                                  But, you can use this to clean up files in an arbitrary directories under your $HOME as well. Say you like to have $HOME/tmp and clean it out every 7 days.

                                                  λ ~ » cat ~/.local/share/user-tmpfiles.d/tmp.conf
                                                  e  %h/tmp - - - 7d
                                                  
                                                  1. 4

                                                    I have ~/tmp on all my machines and for me it combines “not being $HOME” with “only cleaned up when I want to”. Works for me, and I am usually not surprised how large it has become, just sometimes.

                                                    1. 3

                                                      I actually use /tmp in a kind of similar way. I defined this in my shell config:

                                                      function rm () {
                                                        for f in "$@"
                                                        do
                                                          mv -f "$f" "/tmp/$(basename $f)"
                                                        done
                                                      }
                                                      

                                                      This redefines the rm command as a function that just moves the file into /tmp. So if I realize I deleted something by mistake I can have a pretty good chance of getting it back. It’s like a Recycle Bin / Trash for the command line.

                                                      1. 2

                                                        After a few too many regretful deletes, one of the first things I install on a new machine is trash-cli[1] and add an alias for rm=“trash-put”.

                                                        [1] https://github.com/andreafrancia/trash-cli

                                                      2. 2

                                                        Intended for temporary files, /tmp/ is typically where ‘stuff’ that a program doesn’t need in the long-term goes: temporary backups of files you’re working on, your browser caching some content, a holding place for in-progress updates. /tmp/ also has the unique benefit that it is cleared whenever your machine is reset - it is temporary after all.

                                                        So when your computer crashes or power goes down and you have no UPS, you lose edited documents in RAM and also the backups in /tmp.

                                                        Also check file permissions - other users have access to /tmp too.

                                                        In my case, the cycles of reboots and cycles of clearing old temp data are different - the lifetimes do not match. The uptime is usually very long, but sometimes the restart may also come unexpectedly. On the other hand, the temp files should be cleared depending on its age or last access or manually.

                                                        1. 1

                                                          I used to do this too, but occasionally regretted it when a machine rebooted unexpectedly. Instead, I use for a long time now this system: https://leahneukirchen.org/blog/archive/2006/01/keeping-your-home-clean-with-mess.html

                                                          1. 1

                                                            I love using /tmp!!! I don’t have any fancy aliases or functions or whatnot. whenever I want to use /tmp I just do a mkdir /tmp/a (so that it can appear first) and do stuff in there

                                                            intermediary file for uploading somewhere? /tmp/a! thing I downloaded only to experiment with for a few minutes and will never come back to? /tmp/a! banished!

                                                            1. 1

                                                              I went through a phase of reaping $HOME like /tmp; it helped me be explicit about what I wanted to keep dot file wise.