从 runuser 命令传播退出代码
Propagate exit code from runuser command
我想 运行 bash 脚本 StartSomething.sh 作为特定用户。为此,我使用 运行user 命令。我还想知道此 bash 脚本的退出代码。因此,当命令完成或中断时,我将退出代码写入文件。这是代码:
runuser myuser -s /bin/bash -c "./StartSomething.sh --pidfile=${pidfile}; \
echo $? > ${statusfile};" &
sleep 5
pid=$(cat ${pidfile})
while ps -p ${pid} > /dev/null; do sleep 1; done
end=$(cat ${statusfile})
echo "End code: ${end}"
exit ${end}
问题是退出代码仍然是 0,尽管 bash 脚本被中断。有什么问题吗?
如果我有单独的文件,start.sh,使用此代码:
./StartSomething.sh --pidfile=${pidfile}
echo $? > ${statusfile}
和运行用户命令如下所示:
runuser myuser -s /bin/bash -c "./start.sh" &
一切正常。我想使用没有单独文件的第一个示例。有人可以告诉我什么是错的吗?这个问题有更好的解决方案吗?
转义特殊字符 $ 时出现问题。正确命令:
runuser myuser -s /bin/bash -c "./StartSomething.sh --pidfile=${pidfile}; \
echo $? > ${statusfile};" &
将 $?
替换为 $?
。
如果你只想运行程序在后台,等待它完成,我想你也可以使用wait
来获取return值(runuser
通过它,除非发生异常情况):
runuser myuser ./StartSomething.sh --pidfile=${pidfile} &
pid=$!
# do something else
wait $!
echo "it returned $?"
或
runuser myuser ./StartSomething.sh --pidfile=${pidfile} &
pid=$!
echo -n "waiting"
while kill -0 $pid 2>/dev/null; do
echo -n "."
sleep 1
done
echo
wait $!
echo "it returned $?"
我想 运行 bash 脚本 StartSomething.sh 作为特定用户。为此,我使用 运行user 命令。我还想知道此 bash 脚本的退出代码。因此,当命令完成或中断时,我将退出代码写入文件。这是代码:
runuser myuser -s /bin/bash -c "./StartSomething.sh --pidfile=${pidfile}; \
echo $? > ${statusfile};" &
sleep 5
pid=$(cat ${pidfile})
while ps -p ${pid} > /dev/null; do sleep 1; done
end=$(cat ${statusfile})
echo "End code: ${end}"
exit ${end}
问题是退出代码仍然是 0,尽管 bash 脚本被中断。有什么问题吗?
如果我有单独的文件,start.sh,使用此代码:
./StartSomething.sh --pidfile=${pidfile}
echo $? > ${statusfile}
和运行用户命令如下所示:
runuser myuser -s /bin/bash -c "./start.sh" &
一切正常。我想使用没有单独文件的第一个示例。有人可以告诉我什么是错的吗?这个问题有更好的解决方案吗?
转义特殊字符 $ 时出现问题。正确命令:
runuser myuser -s /bin/bash -c "./StartSomething.sh --pidfile=${pidfile}; \
echo $? > ${statusfile};" &
将 $?
替换为 $?
。
如果你只想运行程序在后台,等待它完成,我想你也可以使用wait
来获取return值(runuser
通过它,除非发生异常情况):
runuser myuser ./StartSomething.sh --pidfile=${pidfile} &
pid=$!
# do something else
wait $!
echo "it returned $?"
或
runuser myuser ./StartSomething.sh --pidfile=${pidfile} &
pid=$!
echo -n "waiting"
while kill -0 $pid 2>/dev/null; do
echo -n "."
sleep 1
done
echo
wait $!
echo "it returned $?"