【问题标题】:how to stop exiting from a script?如何停止退出脚本?
【发布时间】:2011-01-23 22:29:41
【问题描述】:

我有一个脚本 A 调用脚本 G 。在脚本 G 中,我无法更改任何内容(没有写入权限)。

脚本 G 内部:

ExitProcess ()
{

  case $1 in
    "0" ) echo "$0: Finished successfully."
          exit 0
      ;;
*)  echo "$0: Unknown return status ($1)"
      exit $1
      ;;
 esac

}

由于我从 Script A 退出,如何阻止它?

脚本 A:

check_status()
{

UserName="sbrk6"
MachineName="sn26"

Tstatus=`ssh -f -T ${UserName}@${MachineName} ps -ef  | grep -w "Manager 1 PR" | egrep -v "grep|less|vi|more"`
Cstatus=`ssh -f -T ${UserName}@${MachineName} ps -ef | grep -w "gt1" | egrep -v "grep|less|vi|more"`

if [ "$Tstatus" ]
then
        if [ "$Cstatus" ]
        then

                Gstatus=`ps -ef  | grep -w "Gth_Hndl" | egrep -v "grep|less|vi|more"`

                if [ -z "$Gstatus" ]
                then
                        genth_start
                fi
        fi
else

        if [ -z "$Tstatus" ]
        then
                if [ -z "$Cstatus" ]
                then

                        Gstatus=`ps -ef  | grep -w "Ghfdjdjd" | egrep -v "grep|less|vi|more"`
                        if [ "$Gstatus" ]
                        then
                                genth_stop
                        fi
                fi
        fi
fi
}


genth_start()
{
echo START

. GD1_Sh 

}


genth_stop()
{
echo STOP

. G_Sh

##This is the Script G ###

}

while :
do
        check_status
done

希望这个 while 循环继续,直到我杀死这个脚本

【问题讨论】:

    标签: shell scripting unix ksh


    【解决方案1】:

    如果您无法更改脚本 G,那么安排将其作为单独的进程运行可能最简单,而不是使用 .(点)命令在当前进程中运行它。

    如果Script G只能在dotted模式下使用,那么你可以编写第三个脚本,叫它Script Z,它的目的是运行Script G并退出,而你的Script A继续愉快地运行(从Z报告错误退出,然后做任何适当的事情)。

    如果这也不可行,那么您可以谨慎使用eval 和$(...),这样当脚本 G 中包含 exit 语句的函数实际退出时,它们会在子 shell 中运行,而不是在您的主壳。这比单独运行脚本 G 更复杂,无论是否使用脚本 Z 包装,所以我会首先使用其中一种机制。

    【讨论】:

    • 如何单独运行?
    • @Kimi:不要使用. ScriptG;使用ScriptG 或sh ScriptG 或一些变体。如果执行它,您将无法调用 ScriptG 中的函数,除非通过命令行参数(或其他环境机制)影响其行为。这就是为什么您最终可能需要 ScriptZ 来包装 ScriptG - 它可以执行 . ScriptG 然后调用您需要调用的函数。
    • @Kimi:或者,在打点ScriptG之后,您可以安排取消定义并重新定义ExitProcess函数,使其不退出。
    【解决方案2】:

    您可以trap exit codes 并调用特定函数。在这种情况下,您不希望在脚本 A 中的函数末尾调用 exit。

    你也可以return an integer而不使用exit。

    来自this comment.的示例代码

    function return_code_test ()
    {
    return 50
    }
    

    【讨论】:

    • 我对在我的脚本 (A) 中调用的脚本 (G) 没有权限。
    • 它正在从脚本 G 退出,没有返回任何东西给脚本 A
    猜你喜欢
    • 2011-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-05
    • 2018-06-28
    • 2023-04-11
    • 2019-10-14
    相关资源
    最近更新 更多