- Where is the temporary directory in Linux?
- 5 Answers 5
- /tmp : Temporary files
- /var/tmp : Temporary files preserved between system reboots
- How to create a temporary directory?
- 6 Answers 6
- Everything Essential About the tmp Directory in Linux
- What is the /tmp directory in Linux?
- Are /tmp and /var/tmp the same? No!
- Automate tmp directory cleaning
- Did you know about the black hole of Linux filesystem?
Where is the temporary directory in Linux?
Does Linux have a standard temporary directory for general use, like Windows’s C:\Temp folder? If so, where is it located? I found an SO question about finding a tmp directory programmatically, but I want to set a temp location in an XML config file ahead of time.
I know this looks like a really easy question, but I couldn’t find a clear, simple answer through searching. Many of the results I got were for program-specific temp directories/files. I did see multiple references to /tmp , but they were ambiguous about whether that’s standard for Linux or just a common convention.
Windows’s C:\Temp is most certainly not standard. Windows 95 already had %TEMP% pointing to C:\WINDOWS\Temp .
5 Answers 5
/tmp : Temporary files
The /tmp directory must be made available for programs that require temporary files.
Programs must not assume that any files or directories in /tmp are preserved between invocations of the program.
Rationale
IEEE standard POSIX.1-2008 lists requirements similar to the above section. Although data stored in /tmp may be deleted in a site-specific manner, it is recommended that files and directories located in /tmp be deleted whenever the system is booted.
FHS added this recommendation on the basis of historical precedent and common practice, but did not make it a requirement because system administration is not within the scope of this standard.
/var/tmp : Temporary files preserved between system reboots
The /var/tmp directory is made available for programs that require temporary files or directories that are preserved between system reboots. Therefore, data stored in /var/tmp is more persistent than data in /tmp .
Files and directories located in /var/tmp must not be deleted when the system is booted. Although data stored in /var/tmp is typically deleted in a site-specific manner, it is recommended that deletions occur at a less frequent interval than /tmp .
TMPDIR This variable shall represent a pathname of a directory made available for programs that need a place to create temporary files.
- /tmp/ should be used for smaller, size-bounded files only; /var/tmp/ should be used for everything else.
- Data that shall survive a boot cycle shouldn’t be placed in /tmp/ .
$ systemd-path temporary /tmp $ systemd-path temporary-large /var/tmp
FreeBSD, NetBSD, OpenBSD and DragonFly have something similar described in the hier(7) man page.
How to create a temporary directory?
The problem is, when it runs to the , there happens to be another program wants to do the same thing, which mkdir-ed a temp dir with the same name, will cause the failure of this program.
6 Answers 6
Use mktemp -d . It creates a temporary directory with a random name and makes sure that file doesn’t already exist. You need to remember to delete the directory after using it though.
This is a OS X vs Linux thing. See this question for a version that works on both: unix.stackexchange.com/questions/30091/…
Why do you say «You need to remember to delete the directory after using it though.»? Doesn’t that kinda defeat the purpose of using a temp directory?
@M.K.Safi I think the main purpose is to create an empty directory where you can store temporary files without cluttering up other parts of the filesystem. You get to choose if/when you want to delete it. If it creates it in /tmp, then it should be cleared when the system restarts anyway.
For a more robust solution i use something like the following. That way the temp dir will always be deleted after the script exits.
The cleanup function is executed on the EXIT signal. That guarantees that the cleanup function is always called, even if the script aborts somewhere.
#!/bin/bash # the directory of the script DIR="$( cd "$( dirname "$" )" && pwd )" # the temp directory used, within $DIR # omit the -p parameter to create a temporal directory in the default location WORK_DIR=`mktemp -d -p "$DIR"` # check if tmp dir was created if [[ ! "$WORK_DIR" || ! -d "$WORK_DIR" ]]; then echo "Could not create temp dir" exit 1 fi # deletes the temp directory function cleanup < rm -rf "$WORK_DIR" echo "Deleted temp working directory $WORK_DIR" ># register the cleanup function to be called on the EXIT signal trap cleanup EXIT # implementation of script starts here .
Directory of bash script from here.
FreeBSD Caution! mktemp on FreeBSD doesn’t have -p option, and cleanup will rm -rf your current directory!
@madfriend really? if mktemp fails, WORK_DIR will be empty, meaning the command would just be rm -rf with no argument. I don’t use FreeBSD but I’d be pretty surprised if rm -rf was equivalent to rm -rf .
@jbg yes, it seems odd to me now too — it shouldn’t be a really big problem. I might have tweaked an old version of this script so that a path to temporary directory was calculated relatively to current directory, resulting in extinction of mankind current directory removal.
To make it better, you can avoid an empty directory or at least contain the problem within a directory using a solution where you do: 1. TMPWORKDIR=$(basename ‘mktemp -d -p /tmp/git/’) and then 2. rmdir /tmp/git/»$
My favorite one-liner for this is
@piggybox Frankly, I’d be very cautious of using rm -r $(pwd) . Consider the possibility that temporary directory creation fails for whatever reason (maybe the /tmp filesystem is full or has been remounted read only due to an error?); then cd $(mktemp -d) will evaluate to cd which changes to the user’s home directory, which would subsequently be deleted.
The following snippet will safely create and then clean up a temporary directory.
The first trap line executes exit 1 command when any of the specified signals is received. The second trap line removes the $TEMPD on program’s exit (both normal and abnormal). We initialize these traps after we check that mkdir -d succeeded to avoid accidentally executing the exit trap with $TEMPD in an unknown state.
#!/bin/bash # set -x # un-comment to see what's going on when you run the script # Create a temporary directory and store its name in a variable. TEMPD=$(mktemp -d) # Exit if the temp directory wasn't created successfully. if [ ! -e "$TEMPD" ]; then >&2 echo "Failed to create temp directory" exit 1 fi # Make sure the temp directory gets removed on script exit. trap "exit 1" HUP INT PIPE QUIT TERM trap 'rm -rf "$TEMPD"' EXIT
While this is an interesting solution for the error handling, a bit more explanation of the advantages and possible shortcomings would be nice.
Don’t suggest TMPDIR as variable name here, as that is typically the system’s temporary directory. en.wikipedia.org/wiki/TMPDIR
Here is a simple explanation about how to create a temp dir using templates.
- Creates a temporary file or directory, safely, and prints its name.
- TEMPLATE must contain at least 3 consecutive ‘X’s in last component.
- If TEMPLATE is not specified, it will use tmp.XXXXXXXXXX
- directories created are u+rwx, minus umask restrictions.
PARENT_DIR=./temp_dirs # (optional) specify a dir for your tempdirs mkdir $PARENT_DIR TEMPLATE_PREFIX='tmp' # prefix of your new tempdir template TEMPLATE_RANDOM='XXXX' # Increase the Xs for more random characters TEMPLATE=$/$.$ # create the tempdir using your custom $TEMPLATE, which may include # a path such as a parent dir, and assign the new path to a var NEW_TEMP_DIR_PATH=$(mktemp -d $TEMPLATE) echo $NEW_TEMP_DIR_PATH # create the tempdir in parent dir, using default template # 'tmp.XXXXXXXXXX' and assign the new path to a var NEW_TEMP_DIR_PATH=$(mktemp -p $PARENT_DIR) echo $NEW_TEMP_DIR_PATH # create a tempdir in your systems default tmp path e.g. /tmp # using the default template 'tmp.XXXXXXXXXX' and assign path to var NEW_TEMP_DIR_PATH=$(mktemp -d) echo $NEW_TEMP_DIR_PATH # Do whatever you want with your generated temp dir and var holding its path
Everything Essential About the tmp Directory in Linux
Learn some crucial things about the /tmp directory. You’ll also learn how it is different from the /var/tmp directory.
If you have been using Linux for a while, you must have come across the /tmp directory.
You may have some idea about it but you probably didn’t pay enough attention to it.
Then there is also a /var/tmp directory that sounds similar.
So in this article, I will walk you through some crucial things that you need to know about the /tmp directory. I’ll also discuss how it is different from the /var/tmp directory.
What is the /tmp directory in Linux?
As the name suggests, the tmp (temporary) directory under root is used to store the data used by the system and user applications to store the data that are needed for a short period of time. Most Linux distributions are preconfigured to empty the tmp directory after each reboot.
Sounds complex? Let me give you an example.
So let’s suppose you are installing software in your system so the installer may store some files that are needed during the installation.
Similarly, while working on a project, your system may store the files in the tmp directory when making changes or they can also be the auto-saved versions of that file.
In simple words, the tmp directory is nothing but a directory used to store the files that are needed temporarily and can be removed once they are no longer needed.
Are /tmp and /var/tmp the same? No!
Yes, there is a significant difference between the /tmp and the /var/tmp directory.
The short answer is how they both deal with the temporary files.
The /tmp directory is used to store the short-lived temporary files whereas the /var/tmp directory is used to store long-lived temporary files.
Want more details? Here you have it!
- Endurance: Generally, the files stored in the /tmp directory are removed at the boot time whereas the files inside /var/tmp are kept even after reboot.
- For user VS Systemwide: Typically, the files inside the /tmp directory can be accessed by every user whereas the files of /var/tmp are mostly user-specific.
- Usage (the most crucial difference): The /tmp directory is used to store the files that are needed for a short time like for the installation of a package. Whereas the /var/tmp directory is used for files that are needed for a longer period of time like system backup or log files.
Automate tmp directory cleaning
As I said earlier, most, if not all, distributions clean the /tmp directory when you reboot your Linux system.
If that’s the case, then why do you need to explicitly clean the /tmp directory? Because you don’t reboot your server everyday like a desktop computer. I mean check the uptime of your server; it might be running for weeks, if not for months and years.
This is not needed for everyone. Only if your server is running low on the disk space, go for the extra effort of automatic tmp directory cleaning.
To automate the cleaning of the tmp directory, the most critical thing is to identify what to remove in the first place.
So the sweet spot is to remove the files that are not used for the last three days and are not owned by the root.
And for that purpose, you can use the find command in the following manner:
sudo find /tmp -type f \( ! -user root \) -atime +3 -delete
But this won’t automate the process.
First, open the root crontab using the following:
If you are using the corn table for the first time, it will ask you to choose your preferred text editor. I will recommend using the nano:
Once done, go to the end of the file in nano using Alt + / and paste the following line into the file:
0 0 * * * sudo find /tmp -type f ! -user root -atime +3 -delete
Save changes and that’s it!
Did you know about the black hole of Linux filesystem?
I’m talking about the /dev/null directory here as whatever is sent there, can not be traced back! Want to know how it can be used? Here you have a detailed guide:
I hope you will find this guide helpful. And if you have any questions or suggestions, leave a comment.