简体   繁体   English

我如何使用Shell脚本原子替换函数

[英]how can i replace function atomically using shell scripts

First:in my shell scripts: 第一:在我的shell脚本中:

[root@localhost ~]# cat  calc.sh 
#! /bin/sh
calc_func()
{

    i=1;
    j=2;
    if [ $i -gt 0 ];then
        return $(($i+$j));
    fi
}   
calc_func  
echo $?

and then, in my text: 然后,在我的文字中:

[root@localhost ~]# cat calc.txt 
sub_func()
{  

    i=100;
    j=200;
    if [ $i -gt 0 ];then
        return $(($i-$j));
    fi

}

and now, i want to replace the funciton body named calc_func in calc.sh with sub_func's body in calc.txt; 现在,我想用calc.txt中的sub_func主体替换calc.sh中名为calc_func的函数主体; let it becomes to this: 让它变成这样:

[root@localhost ~]# cat  calc.sh 
#! /bin/sh
calc_func()
{

    i=100;
    j=200;
    if [ $i -gt 0 ];then
        return $(($i-$j));
    fi

}   
calc_func  
echo $?

i want to achieve it with shell scripts, how can i fix it ? 我想用shell脚本实现它,如何解决? tips:source or export couldn't be use . 提示:无法使用来源或导出。

You can do it fairly easily with head , tail , sed and mv . 您可以使用headtailsedmv相当轻松地完成此操作。 For example: 例如:

head -n 2 calc.sh >tmp.sh
sed -n '/{/,/}/p' calc.txt >> tmp.sh
tail -n2 calc.sh >> tmp.sh
mv calc.sh calc.sh.sav; mv tmp.sh calc.sh

You can do that as a one-liner, or as a short script. 您可以单行执行,也可以短脚本执行。

Your original calc.sh is now in calc.sh.sav and your new calc.sh with the inner block from calc.txt is in calc.sh , eg 您的原始calc.sh现在在calc.sh.sav和新calc.sh从内部块calc.txtcalc.sh ,如

$ cat calc.sh
#! /bin/sh
calc_func()
{

    i=100;
    j=200;
    if [ $i -gt 0 ];then
        return $(($i-$j));
    fi

}
calc_func
echo $?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM