-1

I am a newbie at shell programming.

As I need to deliver a professional shell program, can someone help to clarify the following three topics:

  1. Standard way of creating temporary files and then removal of these files after the program's execution.

  2. How to be certain that these temporary files are created during current program execution, so that we don't accidentally delete other temporary files created by another instance of the same program.

  3. Creation of log files for logging any errors that occur during the command execution.

Any help is much appreciated.

1
  • user261334 your post probably would have had a better response at Stack Overflow..
    – rusty
    Mar 28, 2014 at 4:57

1 Answer 1

4

Try the mktemp command.

Files created by mktemp will be unique within the containing directory.

#!/bin/bash
FILENAME=$(mktemp)
echo "Writing out data to $FILENAME"
echo "This is a test" > $FILENAME
rm $FILENAME

For errors, consider writing the errors out to "Standard Error":

#!/bin/bash
echo "Everything is fine.."
sleep 1
echo "Oh dear. An error happened" 1>&2
exit

That way, you can potentially redirect your script errors to a file.

$ ./myscript 2>/tmp/errors

Alternatively, send your logs to a local syslog server using the "logger" command.

#!/bin/bash
echo "Everything is fine.."
sleep 1
logger -t "MyApp" "Oh dear. An error happened"
exit

[Edited with more information in response to comment: "But i need to know how to create temporary file with predictable name like " temp_file.test", because this i want to use in my programme"]

mktemp can help you there also. If you need the file to have a particular format you can do something like:

$ FILENAME=$(mktemp --tmpdir=/tmp temp_file-XXXXXXXXXX.txt)
$ echo $FILENAME
/tmp/temp_file-HIitKZc0MT.txt

I'd recommend against using temporary filenames in publicly accessible directories (eg: always using "/tmp/MyTempFile.txt") - unless you are very careful, it's reasonably easy for an attacker to do something nasty, and potentially cause problems for you script - eg:

ln -s /etc/passwd /tmp/MyTempFile.txt
(run your application)

or (depending on what you are using the file for):

chmod 444 /tmp/MyFile.txt
echo "evil sql command perhaps" > /tmp/MyFile.txt
1
  • Hi Thanks for you quick response, But i need to know how to create temporary file with predictable name like " temp_file.test", because this i want to use in my programme. Once programme is over, i want to delete this file.Also this file should unique for this run of the programme.
    – user261334
    Mar 26, 2014 at 12:40

Not the answer you're looking for? Browse other questions tagged .