Home » Questions » Computers [ Ask a new question ]

Linux: How do I execute a script in a way that it knows its directory?

Linux: How do I execute a script in a way that it knows its directory?

I need to write a script, which would be called from any location, but needs to run from the directory it resides in. The script should query its directory at runtime.

Asked by: Guest | Views: 216
Total answers/comments: 2
Guest [Entry]

"echo $(dirname $0)

or

echo ${0%/*}"
Guest [Entry]

"Check out the shell variable $_

From the bash manpage:

At shell startup, set to the absolute pathname used to invoke the shell or shell script being executed as passed in the environment or argument list. Subsequently, expands to the last argument to the previous command, after expansion. Also set to the full pathname used to invoke each command executed and placed in the environment exported to that command. When checking mail, this parameter holds the name of the mail file currently being checked."