cloudbud
cloudbud

Reputation: 39

How to check if the symlink as well as directory exists in linux

I have the symlink

data -> /application/madat/gold/gold_lock/Methods96/../data

I would like to check if the symlink exists and the directory exists using shell script.

I have tried this:

#!/bin/bash
if [[ -h data && data -ef application/madat/gold/gold_lock/Methods96/../data ]]; then echo it exists; else echo it does not; fi

But it doesnot work..

Any lead is appreciated.

Upvotes: 0

Views: 5790

Answers (1)

tgo
tgo

Reputation: 1545

You can try something like this

if [[ -L "data" && -d "$(readlink data )" ]]; then
  echo "both exists"
else
  echo "symlink or directory does not exist"
fi

-L will test if it's a symlink, then -d will look if the directory behind the symlink exists.

If there can be other symlinks in the path of the directory, use readlink -f

Update: forgot to say that -hand -L are equivalent but I find the second easier to remember. This was tested on ubuntu, btw.

Upvotes: 6

Related Questions