[Top][All Lists]

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

Re: Making a path absolute portably

From: Eric Blake
Subject: Re: Making a path absolute portably
Date: Wed, 10 Jul 2019 08:13:28 -0500
User-agent: Mozilla/5.0 (X11; Linux x86_64; rv:60.0) Gecko/20100101 Thunderbird/60.7.0

On 7/10/19 6:45 AM, Sébastien Hinderer wrote:
> Dear all,
> I'd need to compute the absolute path of srcdir in a portable way (it's
> okay if it includes symlinks).
> Currently I use
> abssrcdir=$(cd "${srcdir}"; echo $PWD)
> which seems to work fine.
> Is that considered portable enough?

No, because it uses echo instead of printf and it forgot to quote
"$PWD".  If $srcdir begins with '-' or contains \, behavior is
unspecified based on the problems of echo; if it begins with -, it could
cause problems with cd, and if it contains whitespace, then word
splitting is performed (after echo processes multiple arguments instead
of the intended single argument, abssrcdir would end up with a single
space in place of any run of space or tabs in the original). Then thanks
to $(), if $srcdir ends with one or more \n characters you lose those
bytes if you don't add then strip a sentinel.  Of course, it's unusual
for someone to run your script with srcdir=-mean-name or even
srcdir=$'../../mean  \\dir\n', so you may be able to overlook those
issues.  Your next problem is that if $CDPATH is set in the environment,
and $srcdir is relative and matches a hit in CDPATH, then 'cd' produces
output in addition to your echo (not what you wanted).  Finally, if the
cd fails (unusual, but possible if you don't have permissions to change
to the directory), you end up echoing your current location instead of
your intended location.

Fixing all of those items could be done with:

abssrcdir=$(unset CDPATH; cd -- "$srcdir" && printf %sX "$PWD") || fail

but how much portability you actually have to worry about, vs. ignoring
as unlikely, may depend on context of how you expect $srcdir to be

Eric Blake, Principal Software Engineer
Red Hat, Inc.           +1-919-301-3226
Virtualization: |

Attachment: signature.asc
Description: OpenPGP digital signature

reply via email to

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