문제

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!! :)

도움이 되었습니까?

해결책

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
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top