Command in bash shell script to find path to that script?

Is there a command to go inside a bash .sh script that will provide the full path to the directory containing that script?


Solution 1:

See the answers on Get the source directory of a Bash script from within the script itself. The accepted one recommends

#!/bin/bash

DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"

but reading all the answers gives a lot of alternatives (and insights into how shells work).

Solution 2:

The answers here do not always contain best practices, so if you just want the directory echoed on the screen (even when it contains spaces):

#!/bin/bash
echo "My Script is being run from here: $(dirname "$0")"

If you want it into a variable and want . expanded to the full path, you need GNU Readlink first so:

  1. Install homebrew
  2. Install GNU CoreUtils:

    brew install coreutils
    
  3. Use the following script:

    #!/bin/bash
    
    szMyPath=$(dirname "$0")
    
    if [[ $szMyPath =~ ^. ]]; then 
      szMyPath="$(dirname "$(greadlink -f "$0")")" 
    fi
    
    echo "$szMyPath"