Pregunta

So I'm learning some bash and I'm trying to figure out how to get the directory a script is run from. So given that I have my script ~/scripts/bash/myscript, if I execute my scipt like:

user@localhost ~/dir/I/need/to/run/the/script/from $ ~/scripts/bash/myscript

from within my script, how can I get the directory from which it's being executed, so that I get ~/dir/I/need/to/run/the/script/from in this case. Shortcuts like:

DIR=`pwd`
DIR="$(cd "$(dirname "$0")" && pwd)"
DIR=`dirname $0`

as far as I can notice, they all assign the path to the script to DIR, but I'm looking for the path the script was run from.

Any help on this?

Thanks!! :)

¿Fue útil?

Solución

The $PWD variable is probably what you need.

$ cat >/tmp/pwd.bash <<'END'
#!/bin/bash
echo "\$0=$0"
echo "\$PWD=$PWD"
END

$ chmod u+x /tmp/pwd.bash

$ pwd
/home/jackman

$ /tmp/pwd.bash
$0=/tmp/pwd.bash
$PWD=/home/jackman
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top