Post Reply 
 
Thread Rating:
  • 0 Votes - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Unique temp file in BASH
12-28-2009, 07:09 PM (This post was last modified: 12-28-2009 07:24 PM by codecaine.)
Post: #1
Unique temp file in BASH
Sometimes you have a script that saves a temp file to the computer, but you are not the only one running the script. Some probably that my arise is that you may overwrite someone else temp file name, or delete a temp file that someone is still currently using it. The solution I came up with is this. If you use the $$ variable it hold the current pid for the shell script your currently running. If you append this somewhere in your temp file name it will be unique from everyone else's. Here is a example:

Code:
tmpfile=/tmp/myscript.$$
who > $tmpfile
rm $tmpfile

what this code code does is initialize a variable with the directory path /tmp and the name myscript. with a unique pid number at the end. Next i run the who command to see who is all is logged in into the system and send it to the temp file. Lastly I delete the temp file when I am done using it.
Here is a movie script where I implemented this temp file example. I use this script to see what movies I have. Say I wanted to see all the movies names that had 2009 in it. I would do listmovies 2009. All the filenames with 2009 will print the screen.

Code:
#!/bin/bash

#list contents of drive in a mov data file
tmpfile=/tmp/mov.$$
ls /Volumes/drive3 > tmpfile
ls  /Users/jeromescott/Movies/movies  >> tmpfile
ls /Volumes/drive4 >> tmpfile

#if the user did not enter any parameters print the whole list of movies sorted else print movies that are compared to the first parameter the user enters
if [ $# -eq 0 ]; then
        sort tmpfile;
else
        echo "Movies that have the word $1:"
        echo '################################################'
        sort tmpfile | grep -i $1;
        echo '################################################'
fi
#delete movie list file
rm tmpfile;
#exit the shell script
exit 0;

Here is sample output when I type in the word death. listmoves is my script name.
Code:
listmovies death
Movies that have the word death:
################################################
18 fingers of death 2006.avi
9 Deaths of the Ninja 1985.avi
Acts of Death 2007.avi
Dead Like Me Life After Death 2009.avi
Death At A Funeral 2007.avi
Death Defying Acts 2007.avi
Death Note 2 - The Last Name.avi
Death Note 2006.avi
Death On Demand 2008.avi
Death Proof.avi
Death Race 2000.avi
Death Race 2008.avi
Death Sentence 2007.avi
Death To Smoochy (2002).avi
Death Toll 2008.avi
Death Warrior 2009.avi
Duel to the Death 1983.avi
Grindhouse Death Proof 2007.avi
The Death and Life of Bobby Z 2007.avi
The Deaths Of Ian Stone 2007.avi
death of a president assasination in 2007.avi
################################################
Visit this user's website Find all posts by this user
Quote this message in a reply
Post Reply 


Forum Jump:


 Quick Theme: