SHELL-----全局變量與局部變量

變量的作用域:

一、全局變量:

任何地方都生效的變量,默認情況下,腳本主體內定義全局變量,函數內可以用,函數外也可以用

 

[root@server ~]# vim overall.sh 
#!/bin/bash

function fun1() {
    temp=$[ $value + 5 ]
    result=$[ $temp * 2 ]
}

temp=4
value=6

fun1

echo "The result is $result"
if [ $temp -gt $value ];then
    echo "temp is larger"
else
    echo "temp is smaller"
fi
[root@server ~]# sh overall.sh 
The result is 22
temp is larger

 

二、局部變量:

定義方法: local value

[root@server ~]# vim local.sh 
#!/bin/bash

function fun1() {
    local temp=$[ $value + 5 ]
    result=$[ $temp * 2 ]
}

temp=4
value=6

fun1

echo "The result is $result"
if [ $temp -gt $value ];then
    echo "temp is larger"
else
    echo "temp is smaller"
fi
[root@server ~]# sh local.sh 
The result is 22
temp is smaller

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章