首页 文章

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

提问于
浏览
2

我有一个脚本,它将检查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

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

    但是,您可以做的是启动屏幕,弄清楚有关它的一些细节,然后将控制台脚本 in/output 重定向到该屏幕,但是您将无法像在此开始一样将正在运行的脚本重新定向到屏幕进程。例如:

    #!/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
    

    远非完美而混乱。可以使用复制之类的第三方工具从屏幕内部获取脚本的控制台,这可能会有所帮助。但是 cleaner/simpler 仍将(在需要时)在建立该屏幕会话后启动应在该屏幕会话中执行的代码。

    那就是。实际上,我建议您退后一步,问一下您要实现的目标到底是什么,以及为什么要在屏幕上运行脚本。您打算要 attach/detach to/from 吗?因为如果您要使用独立的控制台运行长期进程,则Nohup可能会更简单。

相关问题