How to get the current path of a .sh script?

5

On Linux-based systems whenever I need to use the following command:

#!/bin/bash

BASEDIR=$(dirname "$0")

echo $BASEDIR

I have however read in different places that $(dirname "$0") is not supported by Mac OS X systems and BSD-based systems (apparently both based on Unix).

I saw some alternatives, but all of them always have a criticism, or some mention saying they fail at something.

What I need to know is there any way to get the current script directory in a cross-platfom (unix-like) way?

Another thing, I'd like to know how to get both the actual directory path and the path of a symbolic link.

  

Note: No need to be with bash

    
asked by anonymous 01.08.2016 / 17:51

2 answers

4

Using the command line in Linux, you can use the shell pwd command to get the path of the target directory. However, when executing this command within a directory that is a symbolic link, this command will usually return the path to the symbolic link and not the actual directory pointed to. This behavior is correct and is expected. However, sometimes we need to get the real directory pointed to. For this, suffice:

$ pwd -P 

(shows the path of the actual directory pointed to by the symbolic link when inside the directory)

$ pwd 

(shows symbolic link path when inside directory)

    
01.08.2016 / 18:26
2

It is strange that dirname is not available in BSD and MacOS , since it is a simple program in C , whose code is in several repositories.

For example: here OpenSource Apple and here OpenBSD . Just compile and use.

Anyway, a solution based on the call position path may be useful, as it allows you to always find script :

Here's a proposal to try and see if it works:

script: onde_estou.sh

#!/bin/bash

DIR_RELATIVO="${0%/*}"

DIR_CHAMADA="${PWD}"

SCRIPT_PATH=$DIR_CHAMADA/$DIR_RELATIVO

echo "Desde a posição de chamada:"
echo "--> $DIR_RELATIVO"

echo "Posição de chamada:"
echo "-->$DIR_CHAMADA"

echo "Junção das duas:"
echo "--> $SCRIPT_PATH"

echo " Exemplo de aplicação"
echo "Listar o conteúdo do diretório onde está o script"
ls $SCRIPT_PATH

The script can be called from several different places and always gives a way there. Unfortunately it does some curves:).

    
23.09.2016 / 03:04