What is tmp file in linux

Где временный каталог в Linux?

Есть ли в Linux стандартный временный каталог для общего пользования, например, C:\Temp папка Windows ? Если да, где он находится? Я нашел SO вопрос о программном поиске tmp каталога , но я хочу заранее установить временное местоположение в XML-файле конфигурации.

/ tmp: временные файлы

/tmp Каталог должен быть доступен для программ , которые требуют временных файлов.

Программы не должны предполагать, что какие-либо файлы или каталоги в /tmp них сохраняются между вызовами программы.

обоснование

Стандарт IEEE POSIX.1-2008 перечисляет требования, аналогичные приведенному выше разделу. Хотя данные, хранящиеся в, /tmp могут быть удалены в зависимости от сайта, рекомендуется, чтобы файлы и каталоги, расположенные в /tmp них, удалялись при каждой загрузке системы.

FHS добавил эту рекомендацию на основе исторического прецедента и общепринятой практики, но не сделал ее обязательным требованием, поскольку системное администрирование не входит в сферу применения этого стандарта.

/ var / tmp: временные файлы сохраняются между перезагрузками системы

/var/tmp Каталог доступен для программ , которым требуется временные файлы или каталоги , которые должны сохраняться между перезагрузками системы. Поэтому данные, хранящиеся в, /var/tmp являются более постоянными, чем данные в /tmp .

Файлы и каталоги, расположенные в, /var/tmp не должны быть удалены при загрузке системы. Несмотря на то, что данные, хранящиеся в, /var/tmp как правило, удаляются в зависимости от сайта, рекомендуется, чтобы удаление происходило с меньшей частотой, чем /tmp .

TMPDIR Эта переменная должна представлять путь к каталогу, доступному для программ, которым требуется место для создания временных файлов.

Это старый вопрос, поэтому сегодня есть еще один вариант. Дистрибутивы Linux, на systemd которые полагается (а это 90%), теперь могут использовать $XDG_RUNTIME_DIR каталог ( спецификация XDG Base Directory ) для хранения определенных типов временных файлов. Обычно он находится по адресу /run/user/$uid . Это каталог для пользователя с 700 разрешениями, которые обеспечивают лучшую безопасность. Это tmpfs крепление, которое обеспечивает производительность. Недостатком tmpfs является то, что он должен использоваться только для хранения небольших файлов и сокетов.

Я смотрю на это как на брак /tmp и /var/run .

Да / TMP для общего пользования. Смотрите здесь и здесь О стандарте иерархии файловой системы.

/ tmp / Временные файлы (см. также / var / tmp). Часто не сохраняется между перезагрузками системы.

С некоторыми подробностями, перечисленными в PDF.

Вы не можете заранее выбрать одно временное имя каталога, которое будет работать для любой системы Linux. На самом деле, вы не можете сделать это и в Windows. Согласно статье Википедии о временных папках , временный каталог в Windows определяется переменной среды TEMP. Если бы вы просто использовали c:\Temp в качестве временного каталога в системе Windows, в котором для TEMP установлено другое значение, любая программа, использующая ваш XML-файл для выбора временного каталога, потерпит неудачу.

Короче говоря, системный временный каталог определяется средой во всех известных мне современных операционных системах, включая как Windows, так и любую UNIX-подобную систему. Установка одного статического пути в качестве временного каталога будет работать только до тех пор, пока значения по умолчанию не будут изменены.

Во всяком случае, стандартный временный каталог в типичной системе Linux есть /tmp . Это эквивалент C:\Temp в том смысле, что это только временный каталог по умолчанию, а не универсальный. Даже если /tmp доступно, если пользователь (или система) установил переменную среды TEMP, вместо нее следует использовать значение этой переменной.

Читайте также:  Steam compatibility with windows 10

Вы можете попробовать выбрать временный каталог относительно домашнего каталога пользователя, который вы можете создать.

Источник

How create a temporary file in shell script?

While running a script, I want to create a temporary file in /tmp directory.

After execution of that script, that will be cleaned by that script.

How to do that in shell script?

6 Answers 6

You can make sure that a file is deleted when the scripts exits (including kills and crashes) by opening a file descriptor to the file and deleting it. The file keeps available (for the script; not really for other processes but /proc/$PID/fd/$FD is a work-around) as long as the file descriptor is open. When it gets closed (which the kernel does automatically when the process exits) the filesystem deletes the file.

Use mktemp to create a temporary file

or, to create a temporary directory:

At the end of the script you have to delete the temporary file or directory

mktemp creates file in the /tmp directory or in the directory given with the —tmpdir argument.

Some shells have the feature built-in.

zsh ‘s =(. ) form of process substitution uses a temporary file. For instance =(echo test) expands to the path of a temporary file that contains test\n .

That file is automatically removed, once the command has finished.

bash/zsh on Linux.

Here-documents or here-strings in bash versions prior to 5.1 and zsh are implemented as deleted temporary files (as was the case in the Bourne shell which introduced here-documents in the late 70s).

The file descriptor 3 is connected to a deleted temporary file that contains test\n .

You can get its content with:

If on Linux, you can also read or write to that file via /dev/fd/3 , though with bash version 5.0, you’d first to need to restore write permissions to it (which bash explicitly removes in that version):

(some other shells use pipes, or may use /dev/null if the here doc is empty).

POSIX

There is no mktemp POSIX utility. POSIX however specifies a mkstemp(template) C API, and the m4 standard utility exposes that API with the mkstemp() m4 function by the same name.

mkstemp() gives you a file name with a random part that was guaranteed not to exist at the time the function was called. It does create the file with permissions 0600 in a race-free way.

So, you could do:

Note however that you need to handle the clean-up upon exit, though if you only need to write and read the file a fixed number of times, you could open it and delete it just after creating like for the here-doc/here-string approach above:

You could open the file for reading once, and rewind in between two reads, however there’s no POSIX utility that can do that rewinding ( lseek() ), so you can’t do it portably in a POSIX script ( zsh ( sysseek builtin) and ksh93 ( operator) can do it though).

Источник

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.

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.

Читайте также:  Windows 10 pro 2004 x64 rus by onesmile

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.

This is an old question so today there is another option available. Linux distributions relying on systemd (which is 90% of them) can now use $XDG_RUNTIME_DIR directory (XDG Base Directory Specification) to store certain types of temporary files. It is generally located at /run/user/$uid . This is a per-user directory with 700 permissions which provides better security. This is a tmpfs mount which provides performance. The downside of tmpfs is that it should only be used to keep small files and sockets.

I look at it as a marriage of /tmp and /var/run .

Yes /tmp is for general use. See here and here On the Filesystem Hierarchy Standard.

/tmp/ Temporary files (see also /var/tmp). Often not preserved between system reboots.

With some more details listed in the PDF.

You cannot choose a single temporary directory name ahead of time that will work for any Linux system. In fact, you can’t do that on Windows either. According to Wikipedia’s article on temporary folders, the temporary directory on Windows is determined by the environment variable TEMP. If you were simply using c:\Temp as a temporary directory on a Windows system that set TEMP to something else, then any program using your XML file to choose a temporary directory would fail.

In short, the system temporary directory is determined by the environment on all modern operating systems that I know of, including both Windows and any UNIX-like system. Setting a single static path as your temporary directory will only work as long as the defaults have not been changed.

Anyway, the standard temporary directory in a typical Linux system is /tmp . It is the equivalent of C:\Temp in the sense that it is only the default temporary directory, not universal. Even if /tmp is available, if a user (or the system) has set the TEMP environment variable, the value of that variable should be used instead.

You could try choosing a temporary directory relative to the user’s home directory, which you can create.

Источник

What is tmp directory in Linux?

The /tmp directory contains mostly files that are required temporarily, it is used by different programs to create lock files and for temporary storage of data. … This is a standard procedure for system administration, to reduce the amount of storage space used (typically, on a disk drive).

Can I delete tmp folder Linux?

The directory /tmp means temporary. This directory stores temporary data. You don’t need to delete anything from it, the data contained in it gets deleted automatically after every reboot. deleting from it won’t cause any problem as these are temporary files.

What does tmp folder hold?

Web servers have a directory named /tmp used to store temporary files. Many programs use this /tmp directory for writing temporary data and generally remove the data when it is no longer needed. Otherwise the /tmp directory is cleared when the server restarts.

Читайте также:  Активатор windows server 2012 r2 standard build 9600

Is it OK to delete TMP files?

. CVR files are created by Outlook. They are saved to the [user]AppDataLocalTemp directory. Yes,You can safely delete them.

How do I clear TMP files in Linux?

How to Clear Out Temporary Directories

  1. Become superuser.
  2. Change to the /var/tmp directory. # cd /var/tmp. Caution – …
  3. Delete the files and subdirectories in the current directory. # rm -r *
  4. Change to other directories containing unnecessary temporary or obsolete subdirectories and files, and delete them by repeating Step 3 above.

How long do files stay in TMP Linux?

conf. As you can see the directories /tmp and /var/tmp are scheduled to be cleaned up every 10 and 30 days respectively.

How do I copy files in Linux?

Copying Files with the cp Command

On Linux and Unix operating systems, the cp command is used for copying files and directories. If the destination file exists, it will be overwritten. To get a confirmation prompt before overwriting the files, use the -i option.

What is TMP used for?

In Unix and Linux, the global temporary directories are /tmp and /var/tmp. Web browsers periodically write data to the tmp directory during page views and downloads. Typically, /var/tmp is for persistent files (as it may be preserved over reboots), and /tmp is for more temporary files.

What program opens TMP files?

Open VLC Media Player. Click on “Media” and select the menu option “Open file”. Set the option “All files” and then indicate the location of the temporary file. Click on “Open” to restore the TMP file.

How do I open my temp folder?

To open the temp folder, click Start or go to the Windows 8 Search charm, type %temp% , and select the folder that appears. Once there, you can manually delete files and subfolders.

Is a tmp file a virus?

TMP is an executable file downloaded and used by the virus, Fake Microsoft Security Essentials Alert. … Fake Microsoft Security Essentials attempts to do this by flooding your computer with pop-up alerts telling you that your computer is infected.

How do I fix TMP files?

How to Recover a . tmp File

  1. Click “Start.”
  2. Click “Search.”
  3. Click “For Files or Folders…”
  4. Click “All Files and Folders.” Type the name of the . TMP file you want to recover into the box you see on screen. Then, click the green button. This will search every directory on your computer for the file you’ve specified. Once located, the .

What is $Windows TMP?

“TEMP” folder, as the name suggests, is used to store temporary files and folders which are created by Windows services and many 3rd party software programs. Since the files and folders stored in Temp folder are temporary, its absolutely safe to remove them.

How do I find temp files in Linux?

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.

How do I change the tmp directory in Linux?

To run the Linux installers with an alternate temp directory:

  1. Define the variable INSTALL4J_TEMP, specifying the value as the desired temp location.
  2. Create the temp directory specified for the installer. …
  3. Add the command line switch –J-Djava.io.tmpdir= when launching the installer.

How often is TMP cleared?

The directory is cleared by default at every boot, because TMPTIME is 0 by default. Show activity on this post. While the /tmp folder is not a place to store files long-term, occasionally you want to keep things a little longer than the next time you reboot, which is the default on Ubuntu systems.

Источник

Оцените статью