How to retrieve absolute path given relative How to retrieve absolute path given relative bash bash

How to retrieve absolute path given relative


Try realpath.

~ $ sudo apt-get install realpath  # may already be installed~ $ realpath .bashrc/home/username/.bashrc

To avoid expanding symlinks, use realpath -s.

The answer comes from "bash/fish command to print absolute path to a file".


If you have the coreutils package installed you can generally use readlink -f relative_file_name in order to retrieve the absolute one (with all symlinks resolved)


#! /bin/shecho "$(cd "$(dirname "$1")"; pwd)/$(basename "$1")"

UPD Some explanations

  1. This script get relative path as argument "$1"
  2. Then we get dirname part of that path (you can pass either dir or file to this script): dirname "$1"
  3. Then we cd "$(dirname "$1") into this relative dir and get absolute path for it by running pwd shell command
  4. After that we append basename to absolute path: $(basename "$1")
  5. As final step we echo it