Hunter的大杂烩

May 24, 2018

shell脚本函数调用方式的区别

Filed under: 技术话题 — hunter @ 3:32 pm

用不同的调用方式,执行脚本函数,会导致不同的运行机制:
1. 不取返回值时,函数是在脚本进程空间内运行,因此函数内可以变更脚本全局工作路径或修改脚本全局变量;

2. 如果用 $(function_name) 方法调用,脚本会新起一个进程,在新进程空间内运行函数,因此函数内修改工作路径或脚本全局变量,都是无效的,在离开函数之后,会复原

 

测试脚本如下:

#!/bin/sh

var1=11

function ch_t()
{
        echo -n "in ch_t 1"
        pwd
        cd /data/applog
        echo -n "in ch_t 2"
        pwd
        var1=12
        #sleep 10
}
cd /data/install
echo -n "first:" $var1 " "
pwd
ch_t
echo -n "second:" $var1 " "
pwd
cd /data/install
var1=11
echo -n "reset"
pwd
ret=$(ch_t)
echo $ret
echo -n "third:" $var1 " "
pwd

运行结果:
first: 11 /data/install
in ch_t 1/data/install
in ch_t 2/data/applog
second: 12 /data/applog
reset/data/install
in ch_t 1/data/install in ch_t 2/data/applog
third: 11 /data/install

No Comments

No comments yet.

RSS feed for comments on this post.

Sorry, the comment form is closed at this time.

Powered by WordPress