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"
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"
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"
--
so your code doesn't work with file names containing whitespace, among others. See https://unix.stackexchange.com/questions/131766/why-does-my-shell-script-choke-on-whitespace-or-other-special-characters – Gilles 'SO- stop being evil' Oct 12 '18 at 12:18