Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash script absolute path with OS X

Tags:

bash

path

macos

I am trying to obtain the absolute path to the currently running script on OS X.

I saw many replies going for readlink -f $0. However since OS X's readlink is the same as BSD's, it just doesn't work (it works with GNU's version).

Is there an out-of-the-box solution to this?

like image 332
The Mighty Rubber Duck Avatar asked Sep 30 '22 16:09

The Mighty Rubber Duck


People also ask

How do I find absolute path in Bash?

In this case, first, we need the current script's path, and from it, we use dirname to get the directory path of the script file. Once we have that, we cd into the folder and print the working directory. To get the full or absolute path, we attach the basename of the script file to the directory path or $DIR_PATH.

What is Realpath in Mac?

realpath(1) realpath uses realpath(3) to resolve the path of the filename(s) supplied as arguments and prints the result to stdout. realpath uses realpath(3) to resolve the path of the filename(s) supplied as arguments and prints the result to stdout.

How do I get the path of a Bash script?

The accepted answer to Getting the source directory of a Bash script from within addresses getting the path of the script via dirname $0 , which is fine, but that may return a relative path (like . ), which is a problem if you want to change directories in the script and have the path still point to the script's ...

How do I run a full path in a shell script?

To use full path you type sh /home/user/scripts/someScript . sh /path/to/file is different from /path/to/file . sh runs /bin/sh which is symlinked to /bin/dash . Just making something clear on the examples you see on the net, normally you see sh ./somescript which can also be typed as `sh /path/to/script/scriptitself'.


2 Answers

These three simple steps are going to solve this and many other OS X issues:

  1. Install Homebrew
  2. brew install coreutils
  3. grealpath .

(3) may be changed to just realpath, see (2) output

like image 151
Oleg Mikheev Avatar answered Oct 27 '22 23:10

Oleg Mikheev


There's a realpath() C function that'll do the job, but I'm not seeing anything available on the command-line. Here's a quick and dirty replacement:

#!/bin/bash

realpath() {
    [[ $1 = /* ]] && echo "$1" || echo "$PWD/${1#./}"
}

realpath "$0"

This prints the path verbatim if it begins with a /. If not it must be a relative path, so it prepends $PWD to the front. The #./ part strips off ./ from the front of $1.

like image 124
John Kugelman Avatar answered Oct 28 '22 01:10

John Kugelman