是否有一种简单的方法可以打印file.txt的完整路径?
file.txt = /nfs/an/disks/jj/home/dir/file.txt
<命令>
dir> <command> file.txt
应该打印
/nfs/an/disks/jj/home/dir/file.txt
是否有一种简单的方法可以打印file.txt的完整路径?
file.txt = /nfs/an/disks/jj/home/dir/file.txt
<命令>
dir> <command> file.txt
应该打印
/nfs/an/disks/jj/home/dir/file.txt
当前回答
这很天真,但是我必须使它与POSIX兼容。需要进入文件目录的cd权限。
#!/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}
其他回答
在Mac OSX中,执行以下步骤:
CD到目标文件的目录。 输入下列任意一个终端命令。
Terminalls "`pwd`/file.txt"
echo $(pwd)/file.txt
用实际的文件名替换file.txt。 按回车键
对于Mac OS X,我替换了操作系统附带的实用程序,用更新版本的coreutils替换了它们。这允许你在Mac上访问像readlink -f(文件的绝对路径)和realpath(目录的绝对路径)这样的工具。
Homebrew版本在命令名前附加了一个“G”(GNU工具)——所以等价的是greadlink -f FILE和grealpath DIRECTORY。
关于如何通过Homebrew在Mac OS X上安装coreutils/GNU Tools的说明可以在这篇StackExchange文章中找到。
注意:readlink -f和realpath命令对于非mac Unix用户应该是开箱即用的。
使用指向:
readlink -f file.txt
您可以使用此功能。如果给出的文件名没有相对路径,则假定它在当前工作目录中:
abspath() { old=`pwd`;new=$(dirname "$1");if [ "$new" != "." ]; then cd $new; fi;file=`pwd`/$(basename "$1");cd $old;echo $file; }
用法:
$ abspath file.txt
/I/am/in/present/dir/file.txt
使用相对路径:
$ abspath ../../some/dir/some-file.txt
/I/am/in/some/dir/some-file.txt
文件名中有空格:
$ abspath "../../some/dir/another file.txt"
/I/am/in/some/dir/another file.txt
这将适用于文件和文件夹:
getAbsolutePath(){
[[ -d $1 ]] && { cd "$1"; echo "$(pwd -P)"; } ||
{ cd "$(dirname "$1")" || exit 1; echo "$(pwd -P)/$(basename "$1")"; }
}