[Shell script] 함수, 조건문, 반복문

David·2022년 7월 21일
0
post-thumbnail

함수 실행 𝒇 (x)


- 전역변수랑 같은 이름의 로컬변수

variable="전역변수"

# function 명시 
function test() {
   local variable="로컬변수"
   echo "====================start test()===================="
   echo "local variable=${variable}"
}

echo "variable: ${variable} "
# 함수 실행
test

- 파라미터가 있는 함수


# function 명시하지 않아도 가능
function_param_test() {
 	echo "start function_param_test()"
 	echo "인자값: ${@}"
	echo '안자값[0]: '$1''
}

# 함수 실행
function_param_test "param1" "param2"



🧐 조건문 (if, else if, else)


- 형식

// [공백 조건문 공백] 중요!!

if [ 조건문 ]
then
       실행문
elif [ 조건문 ]
then
       실행문
else
       실행문
fi

- 조건문 코드


#!/bin/bash

num1=$1
num2=$2

if [ ${num1} -gt ${num2} ]
then
   echo 'num1('$num1') > num2('$num2')'
elif [ ${num1} -lt ${num2} ]
then
   echo 'num2('$num2') > num1('$num1')'
else
   echo 'num1('$num1') == num2('$num2')'
fi

- 정수 비교

문자설명
-eq정수 같음
-ne정수 같지 않음
A -gt BA 가 B 보다 크다
A -ge BA 가 B 보다 크거나 같다 (greater or equal)
A -lt BA 가 B 보다 작다
A -le BA 가 B 보다 작거나 같다 (less or equal)

- File Bool

문자설명
-e 파일명파일이 존재하면 true
-d 파일명파일이 디렉토리면 true
-h 파일명파일이 심볼릭 링크 파일이면 true
-f 파일명파일이 일반파일이면 true
-r 파일명파일이 읽기 가능하면 true
-s 파일명파일크기가 0이 아니면 true
-x 파일명파일이 실행 가능하면 true
-w 파일명파일이 쓰기 가능하면 true



🔄 반복문


- 다양한 for문 예제

# 지정된 범위 안에서 반복문
for str in "hello" "world" "..."
do
   echo ${str}
done


# 초기값; 조건값; 증가값을 사용한 반복문
for ((i=1; i<=4; i++)); do
   echo $i
done

# 변수안에서 반복문
data="10 20 30 40"
for x in $data
do
   echo "${x}"
done

# 배열에서 반복문
array=(100 200 300 400)
for arr in ${array[@]}
do
   echo "array value: ${arr}"
done

- while문 예제

count=0
while [ ${count} -le 5 ];
do
   echo ${count}
   # ((count++))
   # ((count+=1))
   count=$((count+1))   # 변수에 연산 => $((연산))
done



👏🏻 포스트를 마치며


Shell Script는 여기까지 정리하면
간단한 기초는 작성 및 읽는데
문제는 없을 것 같습니다.

다음 포스트에서는

Gradle 과 groovy 로 찾아 뵙겠습니다.

profile
공부하는 개발자

0개의 댓글