ShellScript(10) - function(함수)

 

‘function’(함수) 사용방법에 대해 알아보겠습니다.


예제.1 - Create Function

1
2
3
4
5
6
7
#!/bin/bash
function F1()
{
echo 'I like bash programming'
}

F1
I like bash programming


예제.2 - Create function with Parameters

1
2
3
4
5
6
7
#!/bin/bash
Rectangle_Area() {
    area=$(($1 * $2))
    echo "Area is : $area"
}

Rectangle_Area 10 20
Area is : 200


예제.3 - Pass Return Value from Function

1
2
3
4
5
6
7
8
9
10
11
#!/bin/bash
function greeting() {
    str="Hello, $name"
    echo $str

}
    echo "Enter your name"
    read name

val=$(greeting)
    echo "Return value of the function is $val"
Enter your name
kim
Return value of the function is Hello, kim


예제.4 - Using Global Variable

1
2
3
4
5
6
7
8
9
10
#!/bin/bash
function F1()
{
    retval='I like programming'
}

    retval='I hate programming'
    echo $retval
F1
    echo $retval
I hate programming
I like programming


예제.5 - Using Function Command

1
2
3
4
5
6
7
8
#!/bin/bash
function F2()
{
    local  retval='Using BASH Function'
    echo "$retval"
}
    getval=$(F2)  
    echo $getval
Using BASH Function


예제.6 - Using Variable

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#!/bin/bash
function F3()
{
    local arg1=$1

    if [[ $arg1 != "" ]];
    then
        retval="BASH function with variable"
    else
        echo "No Argument"
    fi
}
getval1="Bash Function"
F3 $getval1
    echo $retval
getval2=$(F3)
    echo $getval2
BASH function with variable
No Argument


예제.7 - Using Return Statement

1
2
3
4
5
6
7
8
#!/bin/bash
function F4() {
echo 'Bash Return Statement'
return 35
}

F4
echo "Return value of the function is $?"
Bash Return Statement
Return value of the function is 35