我有一个脚本,它将检查background_logging
是否为true
,如果是,那么我希望脚本的其余部分在新的分离屏幕中运行。
我已尝试使用以下代码:exec screen -dmS "alt-logging" /bin/bash "$0";
。有时会创建屏幕,等等。但是其他时候则什么也不会发生。当它创建屏幕时,它不会运行脚本文件的其余部分,而当我尝试恢复屏幕时,它说是(Dead??)
。
这是整个脚本,我添加了一些注释以更好地解释我想做的事情:
#!/bin/bash
# Configuration files
config='config.cfg'
source "$config"
# If this is true, run the rest of the script in a new screen.
# $background_logging comes from the configuration file declared above (config).
if [ $background_logging == "true" ]; then
exec screen -dmS "alt-logging" /bin/bash "$0";
fi
[ $# -eq 0 ] && { echo -e "\nERROR: You must specify an alt file!"; exit 1; }
# Logging script
y=0
while IFS='' read -r line || [[ -n "$line" ]]; do
cmd="screen -dmS alt$y bash -c 'exec $line;'"
eval $cmd
sleep $logging_speed
y=$(( $y + 1 ))
done < "$1"
以下是配置文件的内容:
# This is the speed at which alts will be logged, set to 0 for fast launch.
logging_speed=5
# This is to make a new screen in which the script will run.
background_logging=true
该脚本的目的是循环遍历文本文件中的每一行,并将其作为命令执行。当$background_logging
为false
时,它可以很好地工作,因此while
循环没有问题。
1 回答
如上所述,这不是完全可能的。具体来说就是脚本中发生的事情:当您执行时,将正在运行的脚本代码替换为屏幕代码。
但是,您可以做的是启动屏幕,弄清楚有关它的一些细节,然后将控制台脚本 in/output 重定向到该屏幕,但是您将无法像在此开始一样将正在运行的脚本重新定向到屏幕进程。例如:
远非完美而混乱。可以使用复制之类的第三方工具从屏幕内部获取脚本的控制台,这可能会有所帮助。但是 cleaner/simpler 仍将(在需要时)在建立该屏幕会话后启动应在该屏幕会话中执行的代码。
那就是。实际上,我建议您退后一步,问一下您要实现的目标到底是什么,以及为什么要在屏幕上运行脚本。您打算要 attach/detach to/from 吗?因为如果您要使用独立的控制台运行长期进程,则Nohup可能会更简单。