简体   繁体   English

如何让我的脚本在 ssh 断开连接后继续运行而不强制它进入后台?

[英]How can I make my script keep running after a ssh disconnect without forcing it to be backgrounded?

If I got a bash script that it's something like this如果我有一个 bash 脚本,它是这样的

#!/bin/bash -p

echo "PART A PID $$" >> "txt$$.txt";

for ((a=1; a<=10; a++))
do
  sleep 1
  echo "PART B$a" >> "txt$$.txt";
done
                                                                                                                                       
echo "PART C" >> "txt$$.txt";

I'm aware that ./script.sh & disown can prevent a script from being stopped when SSH exits, but I want to achieve that without needing to put the script in the background.我知道./script.sh & disown可以防止脚本在 SSH 退出时停止,但我想在不需要将脚本放在后台的情况下实现这一点。

PART A
PART B1
PART B2
PART B3
PART B4
PART B5
PART B6
PART B7
PART B8
PART B9
PART B10
PART C

and getting an output like this.并获得这样的 output。

I want to wait for the cycle to get an ordered output.我想等待周期获得订购的 output。

Note (i don't want nohup)注意(我不想要nohup)

EDIT编辑

I'm doing this because I want to start more than one of this.我这样做是因为我想开始不止一个。

If i do like @Petesh said in the answer如果我确实喜欢@Petesh 在答案中说

#!/bin/bash -p

(
echo "PART A PID $$" >> "txt$$.txt";
for ((a=1; a<=10; a++))
do
  sleep 1
  echo "PART B$a" >> "txt$$.txt";
done
echo "PART C" >> "txt$$.txt";
)& disown

the PID changes. PID 变化。 In this way if I want to stop the process i can't get the original referrer of the pid.这样,如果我想停止进程,我就无法获得 pid 的原始引用。

I want to know if there's something simple to put at the bottom, without upset all the code我想知道是否有一些简单的东西可以放在底部,而不会打乱所有代码

As you've explained it in comments, your real goal is to let your script still run in the foreground by default, but make sure it survives SSH disconnecting.正如您在评论中解释的那样,您的真正目标是让您的脚本在默认情况下仍然在前台运行,但要确保它在 SSH 断开连接后仍然存在。

You can do this without needing disown in any way, though the code needs to be put at the top , not the bottom :您可以在不需要以任何方式disown的情况下执行此操作,尽管代码需要放在顶部,而不是底部

#!/usr/bin/env bash

# redirect all three of stdin, stdout and stderr (not just stdout!)
exec >"txt$$.txt" 2>"err$$.txt" </dev/null

# ignore any SIGHUP signals received
trap : SIGHUP

# ...put the content of your script here

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM