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

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

<命令>

dir> <command> file.txt  

应该打印

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

当前回答

这适用于Linux和Mac OSX:

echo $(pwd)$/$(ls file.txt)

其他回答

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

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

$ which ls
/bin/ls

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

我发现最简单的方法是:

for i in `ls`; do echo "`pwd`/$i"; done

这对我来说很有效。

这很天真,但是我必须使它与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}
you@you:~/test$ ls
file
you@you:~/test$ path="`pwd`/`ls`"
you@you:~/test$ echo $path
/home/you/test/file

在Windows上:

按住Shift键,在Windows资源管理器中右键单击一个文件,会出现一个名为“复制为路径”的选项。 这将复制文件的完整路径到剪贴板。

在Linux上:

您可以使用realpath yourfile命令来获得其他人建议的文件的完整路径。