是否有一种简单的方法可以打印file.txt的完整路径?

file.txt = /nfs/an/disks/jj/home/dir/file.txt

<命令>

dir> <command> file.txt  

应该打印

/nfs/an/disks/jj/home/dir/file.txt

当前回答

你可以把它保存在壳里。Rc或者直接放到控制台

function absolute_path { echo "$PWD/$1"; }
alias ap="absolute_path"

例子:

ap somefile.txt

将输出

/home/user/somefile.txt

其他回答

我知道有一个更简单的方法,但如果我能找到它…

jcomeau@intrepid:~$ python -c 'import os; print(os.path.abspath("cat.wav"))'
/home/jcomeau/cat.wav

jcomeau@intrepid:~$ ls $PWD/cat.wav
/home/jcomeau/cat.wav

另一个Linux实用程序,它做这个工作:

fname <file>

这将适用于文件和文件夹:

getAbsolutePath(){
    [[ -d $1 ]] && { cd "$1"; echo "$(pwd -P)"; } || 
    { cd "$(dirname "$1")" || exit 1; echo "$(pwd -P)/$(basename "$1")"; }
}

这个解决方案使用的命令存在于Ubuntu 22.04上,但通常存在于大多数其他Linux发行版上,除非它们只是为了s'mores而硬核。

在Linux或Mac上获取文件完整路径的最短方法是使用ls命令和PWD环境变量。

<0.o> touch afile
<0.o> pwd
/adir
<0.o> ls $PWD/afile
/adir/afile

你可以用你自己的目录变量d做同样的事情。

<0.o> touch afile
<0.o> d=/adir
<0.o> ls $d/afile
/adir/afile

注意,如果没有标记,ls <FILE>和echo <FILE>是等效的(对于当前目录中的有效文件名称),所以如果你使用echo,如果你愿意,你可以使用ls代替。

如果情况相反,您有完整的路径并想要文件名,只需使用basename命令。

<0.o> touch afile
<0.o> basename $PWD/afile
afile

在类似的场景中,我从其他位置启动cshell脚本。为了设置脚本的正确绝对路径,让它只在指定的目录中运行,我使用了以下代码:

set script_dir = `pwd`/`dirname $0`

$0存储脚本执行的确切字符串。

例如,如果脚本像这样启动:$> ../../test/test.csh, $script_dir将包含/home/abc/sandbox/v1/