<In Story>

Shell Script 함수(Function) 사용하기 // [Unix] [Linux] [Script] [Programming] 본문

Programming/Script

Shell Script 함수(Function) 사용하기 // [Unix] [Linux] [Script] [Programming]

<In Story, Hi story, History> 2015. 6. 7. 12:49

http://blog.redjini.com/281


사용법


1
2
3
function name(){
  shell command
}


예제


1
2
3
4
5
function my_function(){
   echo "my function"
}
 
my_function


지역변수 (Local variables)


1
2
3
4
5
6
7
8
9
10
11
12
13
value=1234;
 
function my_function(){
   local value=5678
   echo "function: value= ${value}"
}
 
echo "before  : value= ${value}"
 
# call my_function
my_function
 
echo "after   : value= ${value}"


실행결과


before  : value= 1234
function: value= 5678
after   : value= 1234


인자 : parameters


1
2
3
4
5
6
7
function my_function(){
   local value=$1
   echo "my_function= ${value}"
}
 
# call my_function
my_function 5678


결과 전달받기


1
2
3
4
5
6
7
8
9
10
#!/bin/sh
function my_function(){
   local value=$1
   echo "my_function= ${value}"
}
 
# call my_function
result=$(my_function 5678)
 
echo "my_function [ ${result} ]"


1
2
3
4
5
6
7
8
9
10
function my_function(){
    echo "argv: $1 $2"
    return 10
}
 
# call my_function
my_function "myname" "acepro"
result=$?
 
echo "my_function [ ${result} ]"


1
2
3
4
5
6
7
8
9
10
function my_function(){
    echo "argv: $1 $2"
    eval "$3='result'"
}
 
# call my_function
result=""
my_function "myname" "acepro" result
 
echo "my_function [ ${result} ]"