是否有一种简单的方法可以打印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}

其他回答

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

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

通常:

find `pwd` | grep <filename>

或者,只针对当前文件夹:

find `pwd` -maxdepth 1 | grep <filename>

对于Mac OS,如果你只是想在查找器中获取文件的路径,控制单击该文件,并向下滚动到底部的“服务”。你有很多选择,包括“复制路径”和“复制完整路径”。单击其中一个将路径放到剪贴板上。

使用指向:

readlink -f file.txt

你可以使用fpn(完整路径名)脚本:

% pwd
/Users/adamatan/bins/scripts/fpn

% ls
LICENSE   README.md fpn.py

% fpn *
/Users/adamatan/bins/scripts/fpn/LICENSE
/Users/adamatan/bins/scripts/fpn/README.md
/Users/adamatan/bins/scripts/fpn/fpn.py

fpn不是一个标准的Linux包,但它是一个免费开放的github项目,你可以在一分钟内设置好。