3

I added this line into my ~/.bashrc

. /mnt/c/Users/enzo/drive/projects/dotfiles/init.sh

And and inside of init.sh I am trying to get the path of init.sh but I am not able to.

I tried this so far:

CURDIR=`/bin/pwd`
BASEDIR=$(dirname $0)
ABSPATH=$(readlink -f $0)
ABSDIR=$(dirname $ABSPATH)
REAL=$(realpath $0)

echo "CURDIR is $CURDIR"
echo "BASEDIR is $BASEDIR"
echo "ABSPATH is $ABSPATH"
echo "ABSDIR is $ABSDIR"
echo "REAL is $REAL"

Output:

CURDIR is /mnt/c/Users/enzo
BASEDIR is /bin
ABSPATH is /bin/bash
ABSDIR is /bin
REAL is /bin/bash

I'm under windows subsystem for linux.

  • I just need this path /mnt/c/Users/enzo/drive/projects/dotfiles/ to make the script working – EnZo Aug 18 '18 at 11:37
6

Just use BASH_SOURCE instead of $0:

realpath ${BASH_SOURCE}

in your script:

REAL=$(realpath ${BASH_SOURCE})
| improve this answer | |
6

When you source a Bash script, $0 will not hold the name of your sourced script, but of the Bash executable.

You should read the value of $BASH_SOURCE instead, so that the absolute path to the directory of your script would be

SCRIPT_DIR="$(realpath "$(dirname "$BASH_SOURCE")")"

Related: choosing between $0 and BASH_SOURCE (Stack Overflow)

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.