获取bash脚本文件所在的目录

前端之家收集整理的这篇文章主要介绍了获取bash脚本文件所在的目录前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如果该脚本文件包含在另一个脚本文件中(使其与 this question不同),如何获取bash脚本文件所在的目录?

/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
为了获取文件,父脚本显然知道子脚本所在的路径.将其设置为变量,然后在子脚本中检查该变量.如果可用,您知道它已被采购并且您可以使用该路径,否则请使用您链接的问题中的常规技巧.
# 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
原文链接:https://www.f2er.com/bash/385118.html

猜你在找的Bash相关文章