How do I get the absolute directory of a file in bash?

前端 未结 7 1742
臣服心动
臣服心动 2020-12-04 14:03

I have written a bash script that takes an input file as an argument and reads it.
This file contains some paths (relative to its location) to additional files used.

相关标签:
7条回答
  • 2020-12-04 15:04

    To get the full path use:

    readlink -f relative/path/to/file
    

    To get the directory of a file:

    dirname relative/path/to/file
    

    You can also combine the two:

    dirname $(readlink -f relative/path/to/file)
    

    If readlink -f is not available on your system you can use this*:

    function myreadlink() {
      (
      cd "$(dirname $1)"         # or  cd "${1%/*}"
      echo "$PWD/$(basename $1)" # or  echo "$PWD/${1##*/}"
      )
    }
    

    Note that if you only need to move to a directory of a file specified as a relative path, you don't need to know the absolute path, a relative path is perfectly legal, so just use:

    cd $(dirname relative/path/to/file)
    

    if you wish to go back (while the script is running) to the original path, use pushd instead of cd, and popd when you are done.


    * While myreadlink above is good enough in the context of this question, it has some limitation relative to the readlink tool suggested above. For example it doesn't correctly follow a link to a file with different basename.

    0 讨论(0)
提交回复
热议问题