2011-08-25 127 views
2

我对Linux Shell脚本非常新颖,并想知道是否有人可以帮我解决以下问题。如何创建一个脚本来顺序执行多个“exec”命令?

我创建了一个脚本我的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 [email protected] "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 [email protected] "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 [email protected] "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 [email protected] "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 [email protected] "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 [email protected] "ntpd -q -g" 
echo Finished synching director-2-2-B 

sleep 2 

echo 

echo 
echo Finished Synching SVT Cluster 2 directors with SMS. 

脚本似乎只有第一exec命令后完成。

周四8月25日12时40分44秒EDT 2011

Synching GTS集群1名董事短信。

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

任何帮助,将不胜感激=)

+0

man exec将解释为什么发生这种情况。摆脱高管,你应该是金。 OTOH这看起来像是一些严重的ntpd滥用! – fvu

+0

你必须告诉我们为什么你需要执行每个ssh。 ':g/exec/s/exec //'(删除所有可执行文件,它应该可以工作)。祝你好运。 – shellter

+0

@fvu:'man sh'可能是一个更好的方法来找出'exec'内置的功能。 – Jens

回答

7

exec整点是到取代当前进程。在shell脚本中,这意味着shell被替换,在exec之后没有任何更新。我疯狂的猜测是:也许你想用&而不是(ssh ... &)背景命令?

如果你只是想按顺序运行sshs,每次等待它完成,只要删除'exec'字。没有必要用exec表示“我想运行this_command”。只需this_command就可以做到。

哦,并且使这个#!/bin/sh脚本;脚本中没有bashism或linuxism。如果可以的话,避免背痛是很好的做法。这样,如果你的老板决定改用FreeBSD,你的脚本可以不加修改地运行。

5

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

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

#!/bin/bash 

command1 & 
command2 & 
command3 & 

exec command4 

流程执行Exec之前树:

bash       < your terminal 
    | 
    +----bash     < the script 
     | 
     +------command1 
     | 
     +------command2 
     | 
     +------command3 

进程执行EXEC后树:

bash       < your terminal 
    | 
    +------command4 
      | 
      +------command1 
      | 
      +------command2 
      | 
      +------command3 

正如你看到的,前三个命令的所有权时,该脚本的bash进程被command4取代被转移到command4

注:

如果command4退出其他命令前,处理树木变成:

init       < unix init process (PID 1) 
    | 
    +------command1 
    | 
    +------command2 
    | 
    +------command3 

虽然所有权应逻辑上已转移到的bash终端处理? Unix的奥秘......

相关问题