在服务脚本中使用环境变量

using environment variables in service script

我在服务脚本中使用环境变量时遇到问题。

在我的服务脚本中,我使用了一个环境变量,即 INSTALL_DIR,其值在不同的系统上可能会有所不同。我必须从 $INSTALL_DIR 获取安装目录,然后我必须启动该服务。当我 运行 设置服务脚本时,环境变量根本没有来源。

是否可以从 INSTALL_DIR 环境变量获取安装目录。我认为的另一个选择是使用 INSTALL_DIR 环境变量动态创建服务脚本。

echo "INSTALL DIR: ${INSTALL_DIR}"
name=`basename [=10=]`
pid_file="/var/run/$name.pid"
get_pid() {
    cat "$pid_file"
}

is_running() {
    [ -f "$pid_file" ] && ps `get_pid` > /dev/null 2>&1
}

Start()
{
    echo "Starting Application"

    if is_running; then
        echo "[`get_pid`] Already Started"
    else
        if [ -z "$user" ]; then
            nohup $INSTALL_DIR/bin/application 2>&1 &
        else
            nohup sudo -u "$user" $cmd 1> $INSTALL_DIR/bin/application 2>&1 &
        fi
        echo $! > "$pid_file"
        if ! is_running; then
            echo "Unable to start, see logs"
            exit 1
        fi
        echo "[`get_pid`] Started"
    fi
}

我正在尝试 运行 使用以下命令的应用程序

service application start

在您的脚本中使用以下代码。

if [[ -z "${INSTALL_DIR}" ]]; then
  echo "INSTALL_DIR is undefined"
else
  INSTALL_DIR=<<your installation directory>>
fi

In my services script ... I have to get the installation directory from $INSTALL_DIR and then i have to start the service.

您的问题并非真正关于 shell 脚本编写,而是关于系统的启动。不幸的是,这个过程因 Linux 分布而异,而且往往没有很好的记录。

例如,man service 说,service 在尽可能可预测的环境中运行 System V 初始化脚本或 upstart 作业,删除大部分环境变量和当前工作目录设置为 /.,但是 man upstart 说:

$ man -k upstart
upstart: nothing appropriate.

不仅如此,service 联机帮助页还专门列出了脚本启动的环境变量。不用说,你的不在其中。

参数化启动脚本的传统方法是将信息放在已知文件中,通常在 /etc 中,然后在脚本中引用该文件。在您的情况下,您可以执行以下操作:

INSTALL_DIR=$(cat /etc/my-install-dir.cfg)

然后进行相应的处理。

可能有一些方法可以强制您的启动支持其他环境变量。但是,迟早,您需要的信息必须存储在文件系统的某个地方。在我看来,最简单的方法是保留一个文件名来保存该信息,然后直接读取该文件。