1

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

0

2 Answers 2

3

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).

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"
    
2
  • The second, longer version is giving me an error: readlink: illegal option -- f. Commented Aug 24, 2019 at 19:01
  • @murray Edited. My apologies for the error. Commented Aug 27, 2019 at 7:12

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.