如果为true,则在新屏幕中运行脚本

时间:2018-12-12 09:07:18

标签: linux bash shell gnu-screen

我有一个脚本,它将检查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_loggingfalse时,它可以很好地工作,因此while循环没有问题。

1 个答案:

答案 0 :(得分:0)

如上所述,这并非完全可能。具体来说就是脚本中发生的事情:exec时,您将正在运行的脚本代码替换为屏幕代码。

您可以做的是启动屏幕,弄清楚它的一些详细信息,然后将控制台脚本重定向到其中/输出到它,但是您将无法将正在运行的脚本重新定向到屏幕进程,就像在屏幕上启动一样。例如:

#!/bin/bash

# Use a temp file to pass cat's parent pid out of screen.
tempfile=$(tempfile)
screen -dmS 'alt-logging' /bin/bash -c "echo \$\$ > \"${tempfile}\" && /bin/cat"

# Wait to receive that information on the outside (it may not be available
# immediately).
while [[ -z "${child_cat_pid}" ]] ; do
        child_cat_pid=$(cat "${tempfile}")
done

# point stdin/out/err of the current shell (rest of the script) to that cat
# child process

exec 0< /proc/${child_cat_pid}/fd/0
exec 1> /proc/${child_cat_pid}/fd/1
exec 2> /proc/${child_cat_pid}/fd/2

# Rest of the script
i=0
while true ; do
    echo $((i++))
    sleep 1
done

远离完美而混乱。使用reptyr之类的第三方工具从屏幕内部获取脚本控制台可能会有所帮助。但是更干净/更简单的方法是(在需要时)在建立之后在该屏幕会话中启动应该执行的代码。

说。实际上,我建议您退后一步,问一下您要实现的目标到底是什么,以及为什么要在屏幕上运行脚本。您是否打算与之连接/分离?因为如果您要使用分离的控制台运行长期进程,那么nohup可能会更简单一些。