[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: Check existence but not dereference symlink
From: |
Andreas Kusalananda Kähäri |
Subject: |
Re: Check existence but not dereference symlink |
Date: |
Fri, 26 Mar 2021 22:46:11 +0100 |
On Fri, Mar 26, 2021 at 04:17:06PM -0500, Peng Yu wrote:
> Hi,
>
> ln -s 1.txt a.txt
> [[ -a a.txt ]]; echo $?
> 1
> [[ -e a.txt ]]; echo $?
> 1
>
> [[ -e path ]] and [[ -e path ]] will deference symlink. If the target
> does not exist, it will return an error.
>
> I want to check the existence of a path without dereferencing symlink.
> I come up with this, but it is a little verbose. Is this the best way
> to do so?
>
> [[ -f path || -h path || -d path ]]
>
> --
> Regards,
> Peng
I would have thought
[[ -h path ]] || [[ -e path ]]
would be enough. This tests whether "path" is a symbolic link, and if
it's not, whether it exists.
With your expression, you're definitely dereferencing
the possible symbolic link at "path" to see whether its target is a
regular file before testing whether it's a symbolic link. (I'm also not
sure why you use -f and -d as it could potentially be any filetype.)
--
Andreas (Kusalananda) Kähäri
SciLifeLab, NBIS, ICM
Uppsala University, Sweden
.