2010-12-01 91 views
9

是否有任何方法来运行bash脚本X,以便如果X调用可执行bash脚本Y然后Y以'sh -eux'开始?bash递归xtrace

X.sh:

./Y.sh 

Y.sh:

#!/bin/sh 
echo OK 
+0

为什么不`#/ bin/sh的在`Y.sh` -eux`? – khachik 2010-12-01 14:47:17

+0

如果有时你必须在没有这个的情况下运行Y.sh,请为Y.sh创建一个包装器,以这种方式调用它,并始终使用X.sh中的包装器。 – Sorpigal 2010-12-01 15:13:49

+1

对X和Y的修改是不可能的,因为它们不是我的 – krvladislav 2010-12-01 15:58:42

回答

14

有可能使用通过导出SHELLOPTS环境变量在父设置相同的外壳选择,使子shell运行。

在你的情况下X.shY.sh不能编辑,我想创建一个包装脚本,简单地调用X.sh之前出口SHELLOPTS

实施例:

#!/bin/sh 
# example X.sh which calls Y.sh 
./Y.sh 

#!/bin/sh 
# example Y.sh which needs to be called using sh -eux 
echo $SHELLOPTS 

#!/bin/sh -eux 
# wrapper.sh which sets the options for all sub shells 
export SHELLOPTS 
./X.sh 

调用X.sh直接显示-eux选项不Y.sh

[[email protected]]$ ./X.sh 
braceexpand:hashall:interactive-comments:posix 

通过wrapper.sh调用它设置显示的选项已经传播到子shell。

[[email protected]]$ ./wrapper.sh 
+ export SHELLOPTS 
+ ./x.sh 
+ ./y.sh 
+ echo braceexpand:errexit:hashall:interactive-comments:nounset:posix:xtrace 
braceexpand:errexit:hashall:interactive-comments:nounset:posix:xtrace 

在GNU bash上测试版本3.00.15(1) - 发布。因人而异。

0

所以我有工具来调试shell脚本:

#!/bin/sh 

    # this tool allows to get full xtrace of any shell script execution 
    # only argument is script name 


    out=out.$1 
    err=err.$1 
    tmp=tmp.$1 

    echo "export SHELLOPTS; sh [email protected] 1>> $out 2>> $err" > $tmp 
    sh -eux $tmp &> /dev/null 
    rm $tmp