如何在 bash 脚本中等待一段时间然后在打开的新终端上暂停当前工作

如何在 bash 脚本中等待一段时间然后在打开的新终端上暂停当前工作

我有一个名为的程序mdr-dev,我执行该程序并打开端口 1022。

打开该端口后,我必须让程序继续运行以保持该端口开放。 问题是它需要一些时间来执行,所以与此同时我应该等待它打开该端口!

一旦端口打开,我想打开一个新终端并ssh通过该端口连接到远程设备。

问题是:如何为此编写 bash 或任何其他脚本?

(我已经尝试过睡眠命令,但它似乎不起作用。)

以下是我迄今为止尝试过的:

#!/bin/bash
echo $MDR_ROOT
mdr-dev --root --mount /opt/tile/home /home --tunnel 1022 22 

mdr-dev上述命令的初始化过程之后,我想要自动打开一个新终端并运行:

ssh -p 1022 root@localhost

当然,我已经尝试过了:

--tunnel 1022 22 &
sleep 5m 
xterm -hold -e ssh -p 1022 root@localhost

但这似乎不起作用......

我该如何继续?

答案1

由于我没有您的mdr-dev程序,因此很难测试,因此这里提供 0.1 版本。请测试并在评论中反馈。

#!/bin/bash  
#
# This script opens a port to tunnel through, then waits for the tunnel to be opened
# and then connects to the correct host using ssh  
# Answer to: http://askubuntu.com/questions/682316/how-to-wait-for-a-while-and-then-suspend-current-work-on-open-new-terminal-in-a

# Copyright (c) Fabby 2015

# This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. See the GNU General Public License for more details.
# You DID NOT receive a copy of the GNU General Public License along with this program as the license is bigger then this program.
# Therefore, see http://www.gnu.org/licenses/ for more details.

# version 0.1   dd 2015-10-08   First version.

### Init ###
declare -r bDebug=false
declare szPortOpen=""
if $bDebug ; then
  set -x
  declare iDebugTimeOut=30 #seconds
fi

### Main ###
echo "$MDR_ROOT"
# open tunnel:
mdr-dev --root --mount /opt/tile/home /home --tunnel 1022 22 &

if $bDebug ; then
  read -t $iDebugTimeOut -p "Hit [Enter] to continue..."
fi

#Wait for the tunnel to open
while [ -z "$szPortOpen" ]
do
  sleep 1m
  netstat -atn | grep ":1022" | (read szPortOpen; )
  if $bDebug ; then
    echo $szPortOpen
    read -t $iDebugTimeOut -p "Hit [Enter] to continue..."
  fi
done

# Now ssh to the server 
xterm -hold -e ssh -p 1022 root@localhost

相关内容