Linux 如何使用其所在目录的工作目录执行任意脚本?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7363946/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I execute an arbitrary script with a working directory of the directory its in?
提问by Stefan Kendall
I need to execute a groovy script file from bash, and I need the script to have a working directory of the directory it exists in.
我需要从 bash 执行一个 groovy 脚本文件,并且我需要该脚本具有它所在目录的工作目录。
That is, in my bash script, I'm doing this:
也就是说,在我的 bash 脚本中,我这样做:
/opt/script/myscript.groovy &
But this seems to set the working directory to /etc/init.d
, the directory I'm calling from. How do I change the working directory for that script to /opt/script
?
但这似乎将工作目录设置为/etc/init.d
我正在调用的目录。如何将该脚本的工作目录更改为/opt/script
?
采纳答案by The Bndr
/etc/init.d
/etc/init.d
probably you are runnig (starting) that script from /etc/init.d
?
可能您正在运行(启动)该脚本/etc/init.d
?
Add cd /opt/script
at the first line of the script
cd /opt/script
在脚本的第一行添加
OR
或者
...to keep it dynamic, add:
cd "$(dirname "$0")"
...为了保持动态,添加:
cd "$(dirname "$0")"
回答by ?imon Tóth
Something like this maybe:
可能是这样的:
SCRIPT=/opt/script/myscript.groovy
pushd `dirname $SCRIPT`
./`basename $SCRIPT`
popd
回答by Johannes Weiss
In bash
putting that in the script works best:
在bash
将在脚本的效果最好:
HERE=$(cd -- $(dirname ${BASH_SOURCE[0]}) > /dev/null && pwd)
cd -- "$HERE"
This will succeed even with the following invocation (of /path/to/script.sh
):
即使使用以下调用(of /path/to/script.sh
),这也会成功:
PATH="/path/to:$PATH" bash script.sh
where HERE=$(dirname $0)
would fail.
哪里HERE=$(dirname $0)
会失败。
Optionally you could also use pwd -P
instead of just pwd
, then $HERE
will contain the realpath (canonicalized absolute pathname) as of man 3 realpath
.
或者,您也可以使用pwd -P
而不仅仅是pwd
,然后$HERE
将包含从man 3 realpath
.
回答by David Santiago Turi?o
If you are using start-stop-daemon inside your /etc/init.d script, you can take advantage of the -d parameter for achieving this:
如果您在 /etc/init.d 脚本中使用 start-stop-daemon,则可以利用 -d 参数来实现此目的:
-d, --chdir path
Chdir to path before starting the process. This is done after the chroot if the -r|--chroot option is set. When not specified, start-stop-daemon will chdir to the root directory before starting the process.