如何查看在newgrp中调用的命令的状态?

如何查看在newgrp中调用的命令的状态?

问题描述:

我有一个csh脚本,需要使用newgrp进行部分运行。为此,它递归地调用它自己。如何查看在newgrp中调用的命令的状态?

#!/bin/csh 
if ($1 == "") then 
    newgrp << ENDGRP 
    ./newgrp_test.csh 2 
    if ($status != 0) then 
     echo "Second run fail" 
     exit 1 
    else 
     echo "Second run success" 
     exit 0 
    endif 
ENDGRP 
    if ($status != 0) then 
     echo "Exiting failure" 
     exit 1 
    else 
     echo "Exiting success" 
     exit 0 
    endif 
endif 

if ($1 == "2") then 
    exit 1 
endif 

问题是我认为它应该保证失败,但我得到了成功的输出。我的输出如下所示:

Second run success 
Exiting success 

为什么我不能在newgrp中读取脚本的状态?

注意我找到了一个解决方法,通过删除newgrp和ENDGRP之间的if块,但我仍然好奇。

变量$status正在被这里的文档里的外壳扩展。所以当newgrp外壳运行它看到if (0 != 0) then而不是if ($status != 0) then(因为if,或任何was successful immediately before the newgrp`命令)。

要么你需要躲避$的这里文档中:

if (\$status != 0) then 

或here文档字的报价部分,以防止扩大从完全发生:

newgrp << 'ENDGRP' 
    ./newgrp_test.csh 2 
    if ($status != 0) then 
     echo "Second run fail" 
     exit 1 
    else 
     echo "Second run success" 
     exit 0 
    endif 
'ENDGRP'