如何从bsh脚本文件中获取目录,当该脚本文件包含在另一个中时(使其与this question不同)?
/script1.sh
. /dir2/script2.sh
/dir2/script2.sh
# echoes "/dir2"
echo whatevergetsthatdir
这是我试图“修复”的脚本
/etc/init.d/silvercar-gameserver (每个实例都是唯一的)
#!/bin/bash
#
# /etc/rc.d/init.d/silvercar-gameserver
#
# Initscript for silvercar game server
#
# chkconfig: 2345 20 80
# description: lalalalala
#CONFIG
BIN=/opt/silvercar-gameserver # Want to get rid of this
CONF=/etc/opt/silvercar-gameserver
. /etc/init.d/functions
. $BIN/gameserver.sh.inc
exit 0
/opt/silvercar-gameserver/gameserver.sh.inc (每次安装都不得更改。在svn中)
# Meant to be included from a script in init.d
# Required input:
# CONF (e.g. /etc/opt/silvercarserver)
# -- Installation config (must provide JSVC, JAVA_HOME)
. $BIN/localconf.sh
# -- Instance config (must provide ASUSER, ASWORK)
. $CONF/conf.sh
PIDFILE=$ASWORK/running.pid
LOGDIR=$ASWORK/log
CLASS=tr.silvercar.gameserver.runner.DaemonGameServer
ARGS=$CONF
start() {
echo "Going to start Gameserver..."
export JAVA_HOME
cd $BIN
$JSVC -jvm server -procname silvercar-gameserver -pidfile $PIDFILE -user $ASUSER -outfile $LOGDIR/stdout -errfile $LOGDIR/stderr \
-cp `cat classpath` -Dlogroot=$LOGDIR $CLASS $ARGS
echo "Gameserver started!"
}
stop() {
echo "Going to stop Gameserver..."
$JSVC -stop -pidfile $PIDFILE $CLASS
echo "Gameserver stopped!"
}
case "$1" in
start)
start
;;
stop)
stop
;;
restart)
stop
start
;;
*)
echo "Usage: /etc/init.d/silvercar-gameserver {start|stop|restart}"
exit 1
;;
esac
答案 0 :(得分:6)
如果你有bash 3.0或更新版本,你可以使用BASH_SOURCE来获得你需要的东西,而不依赖于调用程序来为你设置任何环境变量。请参阅下面的示例:
#test.sh
source some_directory/script2.sh
#some_directory/script2.sh
echo $BASH_SOURCE
echo $(dirname $BASH_SOURCE)
输出将是:
$ ./test.sh
some_directory/script2.sh
some_directory
答案 1 :(得分:5)
为了获取文件,父脚本显然知道子脚本所在的路径。将其设置为变量,然后在子脚本中检查该变量。如果它可用,您知道它已被采购并且您可以使用该路径,否则请使用您链接的问题中的常规技巧。
# script1.sh
RESOURCE_DIR=/dir2
source $RESOURCE_DIR/script2.sh
# script2.sh
if [ -z "$RESOURCE_DIR"]; then
echo $RESOURCE_DIR
else
echo $(dirname $0)
fi