Trying to make an
if statement that checks if a file is a valid symlink (meaning it also exists).
[ -h "$1" -a ! -e "$1" ]
... buut it doesn't work. I want to execute code if the file isn't a valid symlink, or doesn't exist at all.
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It only takes a minute to sign up.Sign up to join this community
If the name in
$1 is a valid symbolic link, then the
-e test would be true. If it's a broken symbolic link, then the
-e test would fail. The test would additionally fail if the name in
$1 does not exist at all.
So, to test whether
$1 is a broken symbolic link, or if it doesn't exist at all, it would be enough to use
if [ ! -e "$1" ]; then ...; fi
The test that you have is better written without the deprecated
if [ ! -e "$1" ] && [ -h "$1" ]; then ...; fi
This tests whether
$1 is an existing broken symbolic link.
Would you want to test for a valid symbolic link, use
if [ -e "$1" ] && [ -h "$1" ]; then ...; fi