Is there an easy way I can print the full path of file.txt
?
file.txt = /nfs/an/disks/jj/home/dir/file.txt
The
echo $(cd $(dirname "$1") && pwd -P)/$(basename "$1")
This is explanation of what is going on at @ZeRemz's answer:
"$1"
dirname "$1"
cd "$(dirname "$1")
into this relative dir && pwd -P
and get absolute path for it. -P
option will avoid all symlinks$(basename "$1")
echo
itfp () {
PHYS_DIR=`pwd -P`
RESULT=$PHYS_DIR/$1
echo $RESULT | pbcopy
echo $RESULT
}
Copies the text to your clipboard and displays the text on the terminal window.
:)
(I copied some of the code from another stack overflow answer but cannot find that answer anymore)
Another Linux utility, that does this job:
fname <file>
I suppose you are using Linux.
I found a utility called realpath
in coreutils 8.15.
realpath file.txt
/data/ail_data/transformed_binaries/coreutils/test_folder_realpath/file.txt
As per @styrofoam-fly and @arch-standton comments, realpath
alone doesn't check for file existence, to solve this add the e
argument: realpath -e file
This is naive, but I had to make it to be POSIX compliant. Requires permission to cd into the file's directory.
#!/bin/sh
if [ ${#} = 0 ]; then
echo "Error: 0 args. need 1" >&2
exit 1
fi
if [ -d ${1} ]; then
# Directory
base=$( cd ${1}; echo ${PWD##*/} )
dir=$( cd ${1}; echo ${PWD%${base}} )
if [ ${dir} = / ]; then
parentPath=${dir}
else
parentPath=${dir%/}
fi
if [ -z ${base} ] || [ -z ${parentPath} ]; then
if [ -n ${1} ]; then
fullPath=$( cd ${1}; echo ${PWD} )
else
echo "Error: unsupported scenario 1" >&2
exit 1
fi
fi
elif [ ${1%/*} = ${1} ]; then
if [ -f ./${1} ]; then
# File in current directory
base=$( echo ${1##*/} )
parentPath=$( echo ${PWD} )
else
echo "Error: unsupported scenario 2" >&2
exit 1
fi
elif [ -f ${1} ] && [ -d ${1%/*} ]; then
# File in directory
base=$( echo ${1##*/} )
parentPath=$( cd ${1%/*}; echo ${PWD} )
else
echo "Error: not file or directory" >&2
exit 1
fi
if [ ${parentPath} = / ]; then
fullPath=${fullPath:-${parentPath}${base}}
fi
fullPath=${fullPath:-${parentPath}/${base}}
if [ ! -e ${fullPath} ]; then
echo "Error: does not exist" >&2
exit 1
fi
echo ${fullPath}
I like many of the answers already given, but I have found this really useful, especially within a script to get the full path of a file, including following symlinks and relative references such as .
and ..
dirname `readlink -e relative/path/to/file`
Which will return the full path of the file
from the root path onwards.
This can be used in a script so that the script knows which path it is running from, which is useful in a repository clone which could be located anywhere on a machine.
basePath=`dirname \`readlink -e $0\``
I can then use the ${basePath}
variable in my scripts to directly reference other scripts.
Hope this helps,
Dave