Temp Files – Bash Scripting

If you use bash scripts on a regular basis for file manipulations you would have come across times where the output had to be written to some temporary files. From which further handling can be done. This is quite common. But surprisingly after years, I have come to know the use of temporary files that the system itself safely creates in the /tmp directory. You do not have to worry about the naming or the location or such. You can use the mktemp command to create a temporary file which can be assigned to a file handler.

Lets look at a very common use. You have some text ready after some processing. You want to write it to a file. What you do before hand is say,
temp_file=$(mktemp)

This will create a tempfile and assign it to the file handler temp_file. Then you will probably want to write some stuff to this file. you can do this by just sending the outputs like this,
echo "my output" > $temp_file

Just using echo here for explanation purposes. You can continue appending your outputs of course, using >>.

You can use this file for further processing in a for loop or something just like you would do any other file. Like for example,

for line in `cat $temp_file`; do

This was one really useful tip because I do not have to worry about the file naming or location of the file or about removing the file later on.

Thanks for reading.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s