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

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

<命令>

dir> <command> file.txt  

应该打印

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

当前回答

这个解决方案使用的命令存在于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

其他回答

除了"readlink -f",还有一个常用的命令:

$find /the/long/path/but/I/can/use/TAB/to/auto/it/to/ -name myfile /the/long/path/but/I/can/use/TAB/to/auto/it/to/myfile $

这也给出了控制台的完整路径和文件名

跑题:这种方法只给出相对链接,而不是绝对链接。readlink -f命令是正确的。

这将为您提供文件的绝对路径:

find / -name file.txt 

我知道这是一个老问题了,但在这里补充一下信息:

Linux命令,可用于查找命令文件的文件路径。

$ which ls
/bin/ls

这里有一些注意事项;请参见https://www.cyberciti.biz/faq/how-do-i-find-the-path-to-a-command-file/。

对于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用户应该是开箱即用的。

这很天真,但是我必须使它与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}