A script may need to create temporary files to hold intermediate results. The safest way to do this is to use
mktemp which returns a currently unused name. The following command creates a new file in
/tmp.
newfile=$(mktemp -c -d /tmp)
If a script is prematurely aborted (the user may press
^C
for example) it's good practise to remove any temporary files. The
trap command can be used to run a tidy-up routine when the script (for whatever reason) exits. To see this in action start the following script then press
^C
newfile=$(mktemp -c -d /tmp)
trap "echo Removing $newfile ; rm -f $newfile" 0
sleep 100
No comments:
Post a Comment