Trying to make an if statement that checks if a file is a valid symlink (meaning it also exists).

I tried:

[ -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.

  • You are using 6 arguments for test and more than 4 args are unspecified. Better divide it into more single purpose tests.
    – schily
    May 13 '20 at 10:44

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 -a as

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.