help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [Question] Reliable way to clean up a directory in EXIT trap


From: Greg Wooledge
Subject: Re: [Question] Reliable way to clean up a directory in EXIT trap
Date: Mon, 18 Jul 2022 13:23:22 -0400

On Tue, Jul 19, 2022 at 02:15:38AM +0900, Masahiro Yamada wrote:
> #!/bin/bash
> set -e
> 
> # use .tmp_<PID> as a temporary workspace
> TMPDIR=.tmp_$$
> 
> trap "rm -rf $TMPDIR" EXIT
> 
> mkdir -p $TMPDIR
> touch $TMPDIR/tmp

The first problem I see with this is that you've used a *relative*
pathname for your TMPDIR variable.  The trap is going to issue a command
of the form "rm -rf .tmp_12345" when your script exits.

What happens if, later on, you modify this script to change directory
somewhere?  If the trap runs after the script has changed directory,
you might be removing that relative pathname from the wrong place.

The second problem is lack of proper quoting -- not going to bite you
right now, because you've restricted your TMPDIR variable to a known
value that doesn't contain whitespace or globbing characters, but proper
quoting is a good habit to develop.  In the future, you'll be using
variables whose contents are *not* safe when used without proper quoting.



reply via email to

[Prev in Thread] Current Thread [Next in Thread]