David542
David542

Reputation: 110392

pwd vs directory of file

I have a file and I want to get the directory that file is in. In python, I would do:

FILE_DIR = os.path.dirname(os.path.realpath(__file__))

How would I do the same thing in a shell script? If I use pwd I would get the current directory of the folder I am executing the command from and not the folder of the file I am executing (which is what I need).

Upvotes: 1

Views: 1791

Answers (2)

isedev
isedev

Reputation: 19641

One solution is:

FILE_PATH=`realpath $0`
FILE_DIR=`dirname $FILE_PATH`

Or in bash-like shells:

FILE_DIR=$(dirname $(realpath $0))

Note that realpath is only guaranteed to be available on GNU-based systems (e.g. Linux).

Upvotes: 2

abarnert
abarnert

Reputation: 365945

When you're executing a shell script, $0 is the name of the script you're executing (see Special Parameters in the Variables chapter of the Bash Guide for Beginners), equivalent to sys.argv[0] in Python (unless you've called shift).

The dirname command does the same thing as os.path.dirname in Python.

There's no portable direct equivalent to os.path.abspath or os.path.realpath, and $0. There are platform-specific ways to do this (e.g., readlink -f on systems with a GNU userland), or you manually combine the pwd with the path. See this question at Unix for a variety of different ways to do that, but mrfripp's answer seems like the most portable:

abspath=$(unset CDPATH && cd "$(dirname "$0")" && echo ${PWD}/$(basename "$0"))

Or, of course, you can just ask Python to do it:

abspath=$(python -c "import os; print(os.path.realpath(\"$0\"))"
absdir=$(dirname "${abspath}")

Upvotes: 3

Related Questions