본문 바로가기
IT/OS

[Linux] shell script 함수의 return

by FreeYourMind 2022. 2. 27.

 

- shell script에서는 return 반환 값이 없음

- shell script 함수의 return 값이 EXIT_STATUS로 전달되며 $?로 확인 가능

- 실행 결과로 받는 EXIT_STATUS의 값: [0 : 성공], [1~255 : 에러]

- $와 () 안에 [명령어 or 함수]를 넣어 sub shell로 실행

- sub shell에서 부모 shell의 변수값을 가져올 수 있지만 sub shell에서 해당 변수를 변경해도 부모 shell에 영향을 미치지 않음

 

 

1. echo를 통해 값 전달

#!/bin/bash

test() {
	result="abcd"
	# echo 함수를 통해서 결과를 전달
	echo "Result is ${result}"
}

ret_value=$(test)	#ret_value=`test`도 가능
echo $ret_value 
# Result is abcd

 

2. 전역 변수 선언으로 값 전달 (전역 변수를 사용해야하므로 좋지 않은 방법)

#!/bin/bash

ret_value=""

test() {
	ret_value="aaaaaaaaa"
}

test
echo $ret_value
// aaaaaaaaa

 

 



출처

https://twpower.github.io/134-how-to-return-shell-scipt-value

https://young-cow.tistory.com/34

 

댓글