0

I want to be able to execute a bash script located in my home directory with the command ~/script_name.sh from any directory and then in the script, get the directory that it was ran from.

eg. I'm in the directory /foo/bar/baz, and execute /foo/script.sh, and it prints out /foo/bar/baz

pwd and $0/$BASH_SOURCE give me the directory my shell starts in and the path to the script in my home directory respectively.

Murd
  • 9
  • 2
  • 3
    `pwd` is the right answer. If you believe seeing something else, please post a [MCVE](https://stackoverflow.com/help/minimal-reproducible-example) – that other guy Jun 02 '20 at 00:01
  • @thatotherguy Is right. Here is a good explanation https://stackoverflow.com/a/1482133/4175515 – Joao Vitorino Jun 02 '20 at 01:37
  • If you add a [mre] letting someone else reproduce the problem, let me know. That said -- `pwd` or, better, `$PWD` is genuinely the right answer here. (BTW -- in the future, tag for bash *or* sh, but not both at once; bash is mostly a superset of the POSIX sh specification, but sometimes they diverge). – Charles Duffy Jun 02 '20 at 12:48

1 Answers1

0

Instead of invoking the external command pwd, consider using $PWD instead. If you want to protect against some rogue code having explicitly changed PWD, do a cd . (which is an internal command) first, which restores PWD to the correct value.

user1934428
  • 19,864
  • 7
  • 42
  • 87