Say I have this simple bash script:

#!/usr/bin/env bash


if [ -z "$file" ]; then
    echo "Must pass relative file path as the first argument.";

git_root=`git rev-parse --show-toplevel`;

#  => need to resolve file from an absolute path to relative path, relative to git root

git diff HEAD:"$file" remotes/origin/dev:"$file"

If I pass an absolute path to this script, it needs to be able to handle it. What is the canonical way to do that? To check if it's an absolute file path, do we just check if the first character is "/"?

1 Answer 1


I am on MacOS, so I had to install coreutils:

brew install coreutils

then we can use realpath like so:

file=`realpath --relative-to="$git_root" "$file"`

or if you need something that works without having to install anything, you can use this node.js script:

#!/usr/bin/env node
'use strict';

const path = require('path');

const file = process.argv[2];
const relativeTo = process.argv[3];

if (!relativeTo) {
  console.error('must pass an absolute path as the second argument.');

if (!file) {
  console.error('must pass a file as the first argument.');

console.log(path.relative(relativeTo, file));

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .