I want to get the full-path director from a script, even if the user enters the './' or '/~'

#!/bin/bash
echo "Enter the directory"
read DIRECTORY #how to store the full-path instead of something like ./
echo "$DIRECTORY"
up vote 0 down vote accepted

Use realpath:

echo "$(realpath $DIRECTORY)"
  • 1
    This removes symbolic links, which is usually not desirable. Also you left out required double quotes and -- so your code doesn't work with file names containing whitespace, among others. See unix.stackexchange.com/questions/131766/… – Gilles Oct 12 at 12:18

For a directory, you can use the command pwd or the variable $PWD.

Example

$ DIRECTORY=.
$ TRUEDIR=$(cd -- "$DIRECTORY" && pwd)
$ echo $TRUEDIR
/home/steve
$

An absolute path begins with /, a relative one doesn't. You can turn a relative path into an absolute path by adding the path to the current directory and a slash before the relative path.

case $DIRECTORY in
  /*) DIRECTORY="$PWD/$DIRECTORY";;
esac

This is portable code: it works in plain sh, not just in bash.

The resulting path may contain symbolic links. This is almost always the right thing, but if you want to canonicalize symbolic links, see Converting relative path to absolute path without symbolic link

You may add a test for an absolute path:

read DIRECTORY
[ "${DIRECTORY:0:1}" = "/" ] || DIRECTORY="$PWD/$DIRECTORY"
echo "$DIRECTORY"

realpath (the accepted answer) is deprecated and not available on most installs. I would use its replacement:

readlink -f "$DIRECTORY"

It too handles ~ and ./ and will follow symbolic links.

If you want to allow the user to enter a $DIRECTORY that does not exist use:

readlink -m "$DIRECTORY"
New contributor
Glenn is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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