18

So, I really like Fish - but I need some help with scripting. and in particular finding the path of the script being run.

Here is the solution for BASH Getting the source directory of a Bash script from within

Can anyone help me find the equivalent with fish?

Community
  • 1
  • 1
Olivier Refalo
  • 50,287
  • 22
  • 91
  • 122
  • Related: [How to get the program name in a fish shell script?](https://stackoverflow.com/questions/16975804/how-to-get-the-program-name-in-a-fish-shell-script) – PhML Jun 18 '14 at 07:43

4 Answers4

27

status --current-filename will output the path to the currently executing script.

For more information on the status command, you can run man status or see the documentation at http://fishshell.com/docs/current/commands.html#status

ridiculous_fish
  • 17,273
  • 1
  • 54
  • 61
  • 3
    That prints out the full path to the file. To get the full path to the directory the script is stored in, use `dirname (status --current-filename)`. – Limeth Apr 14 '16 at 15:39
  • 1
    What if the file is being executed as a symbolic link? `status -f` will print the path of the link, not the actual file. – fiatjaf Dec 25 '16 at 19:59
  • 4
    Answering myself: `dirname (readlink -m (status --current-filename))` – fiatjaf Dec 25 '16 at 20:02
10

In fish shell,

set DIR (cd (dirname (status -f)); and pwd) 

is an equivalent to the BASH one liner

DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

mentioned in Can a Bash script tell what directory it's stored in?.

NOTE: fish shell will cd into that dir and stay there. Bash will cd but it stays contained in subcommand.

hrvoj3e
  • 2,512
  • 1
  • 23
  • 22
  • For the fish shell, to avoid changing the directory, how about: `set DIR (realpath (dirname (status -f)))` ? – piroux Jul 30 '22 at 13:23
5

File path

To get the full path of the script, use status --current-filename, or set FILE (status --current-filename) to declare a variable.

Directory path

To get the full path to the directory the script is stored in, use dirname (status --current-filename), or set DIR (dirname (status --current-filename)) to declare a variable.

The equivalent to this question is the following:

set DIR (dirname (status --current-filename)) is the equivalent

Limeth
  • 513
  • 6
  • 16
  • Using `dirname` directly will only give `.` if run from the same directory, or the directory name if run from another directory. Usually we want an absolute path. – piroux Jul 30 '22 at 13:27
1

Since readlink -m does not exist on macOS,

DIR=dirname (realpath (status -f))

Works on macOS and Linux at the same time.
This solution also has the benefit to work from an .sh file or even the command line.

Olivier Refalo
  • 50,287
  • 22
  • 91
  • 122
  • you should provide a complete answer - provide the complete script code.. this also works from the command line btw. marked as favorite answer, TY – Olivier Refalo Sep 04 '22 at 05:12