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?
While running a script, I want to create a temporary file in After execution of that script, that will be cleaned by that script. How to do that in shell script? |
||||
|
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
|
|||||||||
|
If you're on system which has mktemp, you should use it as other answers. With POSIX toolchest:
|
|||||||||||||||||||||
|
Some shells have the feature built-in. zsh
That file is automatically removed, once the command has finished. bash/zsh on Linux.Here-files or here-strings in So if you do:
The file descriptor 3 is connected to a deleted temporary file that contains You can get its content with:
If on Linux, you can also read or write to that file via
(some other shells use pipes, or may use |
|||||||||
|
Use
Or for a direcotry:
At the end of the script you have to delete the temporary file/dir:
mktemp creates file in the |
|||||||||
|