gpt4 book ai didi

linux - 运行服务启动脚本时未加载环境变量

转载 作者:太空宇宙 更新时间:2023-11-04 10:22:38 25 4
gpt4 key购买 nike

当我使用 ./script start 启动服务脚本时能够通过代理获取凭据(找到环境变量),如果我像 service script start 一样启动服务脚本则无法通过代理获取凭据(未找到环境变量) , 找不到代理。我如何通过服务脚本启动来运行此脚本?

脚本:

#!/bin/bash -l
# chkconfig: 2345 20 80

if [ "$system" = "redhat" ]; then
## source platform specific external scripts
. /etc/init.d/functions
## set or override platform specific variables
lockfile=${LOCKFILE-/var/lock/subsys/$SERVICE_NAME}

## set or override platform specific functions
start_daemon() {
daemon --user $1 --pidfile $2 "$3 $4"
}
log_daemon_msg() {
echo -n $"$1"
}
echo_ok() {
echo_success; echo
}
echo_fail() {
echo_failure; echo
}
log_success_msg() {
success $"$@"
}
log_failure_msg() {
failure $"$@"
echo $"$@"
}
log_action_msg() {
echo $@
}
fi

if [ -n "$http_proxy" ] ; then
echo "proxy found"
echo $http_proxy | grep "@"
if [ $? -eq 0 ]; then
PROXY_HOST=$(echo $http_proxy | sed 's/http:\/\/.*@\(.*\):.*/\1/')
PROXY_PORT=$(echo $http_proxy | sed 's/http:\/\/.*@.*:\(.*\)/\1/' | tr -d "/")
USERNAME=$(echo $http_proxy | sed 's/http:\/\/\(.*\)@.*/\1/'|awk -F: '{print $1}')
PASSWORD=$(echo $http_proxy | sed 's/http:\/\/\(.*\)@.*/\1/'|awk -F: '{print $2}')
else
PROXY_HOST=$(echo $http_proxy | sed 's/http:\/\/\(.*\):.*/\1/')
PROXY_PORT=$(echo $http_proxy | sed 's/http:\/\/.*:\(.*\)/\1/' | tr -d "/")
fi
fi

start() {

echo "Starting $SERVICE_NAME ..."
if [ ! -f $PID_PATH_NAME ]; then
CMD="java "
if [ -n "$PROXY_HOST" -a -n "$PROXY_PORT" ] ; then
CMD="java -Dhttps.proxyHost=$PROXY_HOST -Dhttps.proxyPort=$PROXY_PORT"
if [ -n "$USERNAME" -a -n "$PASSWORD" ]; then
CMD="$CMD -Dhttps.proxyUser=$USERNAME -Dhttps.proxyPassword=$PASSWORD"
fi
fi
#nohup $CMD -jar $PATH_TO_JAR /tmp 2>> /dev/null >> /dev/null &
#echo "$PATH_TO_JAR"
echo "$CMD"
nohup $CMD -jar $PATH_TO_JAR 2>> /tmp/glog >> /tmp/glog &
echo $! > $PID_PATH_NAME

echo "$SERVICE_NAME started ..."
else
echo "$SERVICE_NAME is already running ..."
fi
}
case "$1" in
start)
start
;;
*)
echo "Usage: $0 {start|stop|status|restart}"
esac

exit 0

当我运行此脚本(如 ./script start)时,脚本能够找到代理设置并传递代理设置。但是在使用服务脚本启动时无法找到代理设置。在使用服务运行脚本时,我是否错过了加载环境变量的任何内容?

最佳答案

来自人工服务:

service runs a System V init script in as predictable environment as possible, removing most environment variables and with current working directory set to /.

因此,当您尝试运行服务脚本时,只剩下几个环境变量,如 TERMLANG、您的 http_proxy https_proxy 被丢弃。要使用您需要的环境变量,您可以在文件 /etc/default/yourservice 中定义它们:

http_proxy=http://yourproxy.com
https_proxy=http://yourproxy.com

并在脚本的开头source它:

[ -f /etc/default/yourservice ] && . /etc/default/yourservice

关于linux - 运行服务启动脚本时未加载环境变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43196995/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com