如何创建一个脚本来顺序执行多个"exec"命令?

use*_*558 3 shell

我是Linux Shell Scripting的新手,想知道是否有人可以帮我解决以下问题.

我创建了一个脚本来与我的linux机器同步时间,但只有一个exec命令似乎完成

#!/bin/bash
#Director SMS Synch Time Script

echo The current date and time is:
date
echo

echo Synching GTS Cluster 1 directors with SMS.
echo
echo Changing date and time for director-1-1-A
exec ssh root@128.221.252.35 "ntpd -q -g"
echo Finished synching director-1-1-A
echo

sleep 2

echo Changing date and time for director-1-1-B
exec ssh root@128.221.252.36 "ntp -q -g"
echo Finished synching director-1-1-B
echo

sleep 2

echo Finished Synching GTS Cluster 1 directors with SMS.
sleep 2
echo
echo Synching SVT Cluster 2 directors with SMS.
echo
echo Changing date and time for director-2-1-A
exec ssh root@128.221.252.67 "ntpd -q -g"
echo Finished synching director-2-1-A
echo

sleep 2

echo Changing date and time for director-2-1-B
exec ssh root@128.221.252.68 "ntpd -q -g"
echo Finished synching director-2-1-B
echo

sleep 2

echo Changing date and time for director-2-2-A
exec ssh root@128.221.252.69 "ntpd -q -g"
echo Finished synching director-2-2-A
echo

sleep 2

echo Changing date and time for director-2-2-B
exec ssh root@128.221.252.70 "ntpd -q -g"
echo Finished synching director-2-2-B

sleep 2

echo

echo
echo Finished Synching SVT Cluster 2 directors with SMS.
Run Code Online (Sandbox Code Playgroud)

该脚本似乎只在第一个exec命令后完成.

2011年8月25日星期四12:40:44

将GTS Cluster 1控制器与SMS同步.

更改导演1-1-A的日期和时间

任何帮助将不胜感激=)

Jen*_*ens 8

重点exec取代目前的流程.在shell脚本中,这意味着shell被替换,并且在exec执行之后不再执行任何操作.我疯狂的猜测是:也许你想用&instead(ssh ... &)来背景命令?

但是,如果您只是想按顺序运行ssh,每次等到它完成后,只需删除'exec'字样即可.没有必要表达"我想运行this_command" exec.只是this_command会做的伎俩.

哦,把它变成一个#!/bin/sh剧本; 你的脚本中没有bashism或linuxism.如果可以的话,最好避免使用bashisms.这样,如果您的老板决定切换到FreeBSD,您的脚本可以不加修改地运行.


ear*_*rey 6

你可以在后台运行所有命令,但是最后一个是exec:

例如,如果您有4个命令:

#!/bin/bash

command1 &
command2 &
command3 &

exec command4
Run Code Online (Sandbox Code Playgroud)

执行exec之前处理树:

bash                         < your terminal
  |
  +----bash                  < the script
         |
         +------command1
         |
         +------command2
         |
         +------command3
Run Code Online (Sandbox Code Playgroud)

执行exec后进程树:

bash                         < your terminal
  |
  +------command4
            |
            +------command1
            |
            +------command2
            |
            +------command3
Run Code Online (Sandbox Code Playgroud)

如您所见,前三个命令的所有权将转移到command4脚本的bash进程被command4替换的情况

注意:

如果command4在其他命令之前退出,则进程树变为:

init                         < unix init process ( PID 1 )
  |
  +------command1
  |
  +------command2
  |
  +------command3
Run Code Online (Sandbox Code Playgroud)

虽然所有权应该在逻辑上已经转移到bash终端进程?Unix神秘......