≡ Menu

temporary file

This happens lot of times. I login as a normal user and start to edit httpd.conf or lighttpd.conf or named.conf in vim / vi text editor. However, I'm not able to save changes due to permission issue (all config files are owned by root). How do I save file without creating a temporary file (/tmp/httpd.conf) and then move the same (mv /tmp/httpd.conf /etc/httpd) as root using vim / vi itself?
[click to continue…]

BASH: Prepend A Text / Lines To a File

Q. I can append text to a file using >> operator but how do I prepend a text to a file? I want the opposit of >> operation?
[click to continue…]

How to: create a temporary file securely

Q. How do I create a temporary file securely under UNIX Bash shell?

A. There are many ways:
[a] mktemp command - make temporary unique filename

[b] $RANDOM - Use $RANDOM variable

mktemp command

From the man page:

The mktemp utility takes the given filename template and overwrites a portion of it to create a unique filename. The template may be any filename with some number of ‘Xs’ appended to it, for example /tmp/tfile.XXXXXXXXXX.

For example, create a temporary file:
$ mktemp /tmp/output.XXXXXXXXXX
Output:

/tmp/output.qBYDtF7199

Send ls command output to /tmp/output.qBYDtF7199:
$ ls > /tmp/output.qBYDtF7199
However, you may need to store temporary file name /tmp/output.qBYDtF7199 to a shell variable:
TMPFILE=$(mktemp /tmp/output.XXXXXXXXXX)
ls > $TMPFILE

Create a temporary directory

The -d option makes a directory instead of a file.
TMPDIR=$(mktemp -d /tmp/output.XXXXXXXXXX)
cd $TMPDIR
# do something

Another example:

TMPFILE=‘mktemp -t /tmp/out.myapp.XXXXXXXXXX‘ && {
    # Safe to use $TMPFILE in this block
    echo data > $TMPFILE
    ...
   # do something
   # clean up
    rm -f $TMPFILE
}

Using $RANDOM variable

Bash also provide $RANDOM variable with random value, you can use the same to create a file or directory:

TEMFILE=/tmp/$RANDOM
> $TEMFILE
# create directory
TEMDIR=/tmp/$RANDOM.$RANDOM
mkdir $TEMDIR
# do something...