kcstricks
kcstricks

Reputation: 1579

Bash: check if a relative path exists

I am writing a shell script that takes in a directory as its only argument. I need to check if the directory exists before I do anything else. The directory can be absolute or relative. I know I can check for the existence of an absolute directory (say, /Users/keith/Documents/TestFolder) using

if [ -d "$1"]; then
    # do something if the absolute directory exists
fi

However, if the working directory is /Users/keith/Documents/ and I call my script and pass just "TestFolder", then the test in this if statement will evaluate to false, even though TestFolder exists within the current working directory.

I have tried converting the directory to an absolute directory using

abs_path=`cd "$1"; pwd`

and then testing for the existence of the absolute path using the if statement above. This works fine (recognizes that "TestFolder" exists even if that's all that I pass as the argument) provided that the directory passed to the script does indeed exist, but if it doesn't then this fails.

What I need is a way to determine whether the directory passed as an argument exists, regardless of whether it is passed as an absolute directory or one that is relative to the user's current working directory, and it cannot fail if the directory doesn't exist.

I am clearly no bash expert - any advice will be greatly appreciated!

Upvotes: 3

Views: 13056

Answers (2)

User51
User51

Reputation: 1109

A simple solution would be to...

  1. turn off fail on error
  2. Try to CD and pwd (which may or may not fail)
  3. Turn on fail on error (if desired)
set +e
TESTPATH="$( cd ~/workspace/my-super-folder && pwd )"
set -e

Once you have the variable TESTPATH, you can test that. If the path is in the variable, the directory exists. If the path is empty, it doesn't.

if [[ "${TESTPATH}" == "" ]]; then
  echo -e "FOLDER DOES NOT EXIST."
else
  echo -e "FOLDER EXISTS."
fi

Upvotes: -1

rici
rici

Reputation: 241971

However, if the working directory is /Users/keith/Documents/ and I call my script and pass just "TestFolder", then the test in this if statement will evaluate to false, even though TestFolder exists within the current working directory.

That's not correct. If TestFolder exists in the current working directory, [ -d TestFolder ] will succeed. So there is no problem here.

By the way, if you want to canonicalize a filepath and you have Gnu coreutils (which you probably do if you have a Linux system), then you can use:

readlink -f "$path"

or

readlink -e "$path"

The difference is that -f will succeed even if the last component in the path doesn't exist (so it will succeed if the path is a plausible name for a file to be created), while -e will only succeed if the path resolves to an existing file or directory. See man readlink for more details.

Upvotes: 8

Related Questions