The mcookie shell command is used to generate magic cookie for xauth. It throws a md5sum like output and the basic usage is as shown below.

[neo@techpulp ~]# mcookie
5f8dbb14e7eb4db75428017585115feb
[neo@techpulp ~]#

Now let us use the output of mcookie command and form a random file name for temporary usage. In the following script, we use first characters of the random string printed by mcookie to form a random file name. The randfile() function takes prefix and suffix of the temporary file name and returns a temporary file name after checking for its existence.

#!/bin/bash

function randfile
{
        while [ 1 ];
        do
                MCOUT=`mcookie`
                TNAME="$1""${MCOUT:0:5}""$2"
                if [ ! -f $TNAME ]; then
                        echo $TNAME
                        exit 0
                fi
        done
}

NAME=`randfile /tmp/test- .tmp`

echo $NAME

The output will be as follows if the script is run.

[neo@techpulp ~]# sh mcrand.sh
/tmp/test-efb1a.tmp
[neo@techpulp ~]# sh mcrand.sh
/tmp/test-9b281.tmp
[neo@techpulp ~]# sh mcrand.sh
/tmp/test-e7a1f.tmp
[neo@techpulp ~]# sh mcrand.sh
/tmp/test-a2aed.tmp
[neo@techpulp ~]# sh mcrand.sh
/tmp/test-e8d09.tmp
[neo@techpulp ~]# sh mcrand.sh
/tmp/test-99270.tmp

ALSO READ: How to generate random/temporary file name using RANDOM environment variable