쉘 스크립팅 파트 3: 쉘 스크립트의 의사결정 제어 구조
이 페이지에서
- 소개
- If 문
- 일반 구문
- 파일 기반 조건
- 파일 기반 의사 결정
- 문자열 기반 조건
- 산술 기반 조건
안녕! 이 자습서의 이전 부분(2부)에서 입력 수락, 산술 연산을 통한 데이터 처리, 출력 생성 및 표시와 같은 셸 스크립팅의 기본 사항을 이미 다뤘습니다. 이 파트에서는 프로그램에서 결정을 내리는 프로그래밍 언어의 고급 주제에 대해 더 깊이 들어가지만 이번에는 bash 셸을 사용하여 결정합니다. 시작하자!
소개
오늘날 대부분의 프로그래밍 언어는 우리가 설정한 조건에 따라 결정을 내릴 수 있습니다. 조건은 부울 값(true 또는 false)으로 평가되는 표현식입니다. 모든 프로그래머는 프로그램에 넣은 결정과 논리에 따라 프로그램을 스마트하게 만들 수 있습니다. bash 셸은 if 및 switch(case) 결정 문을 지원합니다.
if 문
If는 프로그래머가 지정한 조건에 따라 프로그램에서 결정을 내릴 수 있도록 하는 문입니다. 조건이 충족되면 프로그램은 특정 코드 줄을 실행하고 그렇지 않으면 프로그램은 프로그래머가 지정한 다른 작업을 실행합니다. 다음은 bash 셸에서 지원되는 if 문의 구문입니다.
일반 구문
단일 결정:
if <condition>
then
### series of code goes here
fi이중 결정:
if <condition>
then
### series of code if the condition is satisfied
else
### series of code if the condition is not satisfied
fi다중 if 조건:
if <condition1>
then
### series of code for condition1
elif <condition2>
then
### series of code for condition2
else
### series of code if the condition is not satisfied
fi단일 대괄호 구문
if [ condition ]
then
### series of code goes here
fi이중 대괄호 구문
if ((condition))
then
### series of code goes here
fi단일 대괄호 구문은 bash 셸에서 지원되는 가장 오래된 구문입니다. Linux의 모든 조건문과 함께 사용됩니다. 한편, 이중 괄호 구문은 프로그래머에게 친숙한 구문을 제공하기 위해 숫자 기반 조건문에 사용됩니다. 모든 유형의 if 문은 작업을 실행하기 위해 지정된 조건이 필요합니다.
Linux의 조건문
조건문은 의사결정 제어문과 함께 사용됩니다. bash 셸에서 사용할 수 있는 다양한 유형의 조건문이 있으며 가장 일반적인 조건은 파일 기반, 문자열 기반 및 산술 기반 조건입니다.
파일 기반 조건
파일 기반 조건은 단항식이며 파일 상태를 검사하는 데 자주 사용됩니다. 다음 목록은 bash 셸에서 가장 일반적으로 사용되는 파일 기반 조건을 보여줍니다.
Operator Description -a file Returns true if file exists -b file Returns true if file exists and is a block special file -c file Returns true if file exists and is a character special file -d file Returns true if file exists and is a directory -e file Returns true if file exists -r file Returns true if file exists and is readable -s file Returns true if file exists and has a greater size that zero -s file Returns true if file exists and has a greater size that zero -w file Returns true if file exists and is writable -x file Returns true if file exists and is executable -N file Returns true if the file exists and has been modified since it was last read 파일 기반 의사 결정
bash 스크립트에서 파일 기반 결정을 구성하는 방법을 설명하는 예제를 살펴보겠습니다. 이 예에서는 파일이 홈 디렉터리에 있는지 확인하는 스크립트를 만듭니다.
#!/bin/bash
cd
ls
if [ -e sample.sh ]
then
echo "file exists!"
else
echo "file does not exist"
fi이 예에서는 cd 명령을 사용하여 현재 활성 디렉토리에 관계없이 쉘이 홈 디렉토리로 돌아가도록 했습니다. 또한 ls 명령어는 파일이 실제로 존재하는지 여부를 확인할 수 있도록 디렉터리의 파일 목록을 표시하는 데 사용됩니다. 보시다시피 스크립트는 "file exists!"라는 텍스트를 출력합니다. sample.sh가 홈 디렉토리에 있기 때문입니다.
Note: The shell compiler is very strict in terms of syntax especially with spaces. There should be a space between if and the open bracket and in between brackets and the condition.
이제 사용자가 스크립트 이름을 입력하고 지정된 파일의 권한을 결정할 수 있도록 하여 코드를 보다 동적으로 만들어 스크립트를 개선해 보겠습니다.
#!/bin/bash
cd
ls -l
read -p "Enter a file name: " filename
if [ -e $filename ]
then
echo "file exists!"
if [ -r $filename ]
then
status="readable "
fi
if [ -w $filename ]
then
status=$status"writable "
fi
if [ -x $filename ]
then
status=$status"executable"
fi
echo "file permission: "$status
else
echo "file does not exist"
fi문자열 기반 조건
문자열 사용자 입력을 기반으로 결정을 내리는 것도 bash 셸에서 가능합니다. 문자열 기반 조건은 결과 의미로 이진 표현식을 반환합니다. 지정된 조건이 충족되면 true를 반환하고 그렇지 않으면 false를 반환합니다. 다음은 일반적으로 사용되는 문자열 기반 조건부 연산자입니다.
Operator Description == Returns true if the strings are equal != Returns true if the strings are not equal -n Returns true if the string to be tested is not null -z Returns true if the string to be tested is null 문자열 기반 조건문을 사용하여 샘플 스크립트를 생성해 보겠습니다. 이 스크립트는 사용자가 두 개의 문자열을 입력하고 문자열 중 하나가 null인지, 두 문자열이 같은지 또는 같지 않은지 평가할 수 있도록 합니다.
#!/bin/bash
read -p "First String: " str1
read -p "Second String: " str2
if [ -z "$str1" ]
then
echo "The 1st string is null"
elif [ -z "$str2" ]
then
echo "The 2nd string is null"
else
if [ $str1 == $str2 ]
then
echo "The strings are equal"
else
echo "The strings are not equal"
fi
fi산술 기반 조건
쉘은 산술 기반 조건을 선언하는 여러 가지 방법을 제공합니다. 하나는 구식 괄호 구문과 함께 사용할 수 있는 니모닉을 사용하는 것이고, 다른 하나는 이중 괄호와 함께 사용할 수 있는 수학 친화적인 기호를 사용하는 것입니다.
다음은 쉘에서 산술 기반 조건문에 사용할 수 있는 니모닉 목록입니다.
Operator Usage/Description -eq Equal -ge Greater Than or Equal -gt Greater Than -le Less Than or Equal -lt Less Than -ne Not Equal 사용자로부터 정수를 받고 정수가 0, 음수, 홀수 또는 짝수인지 결정하는 스크립트를 생성해 보겠습니다.
#!/bin/bash
read -p "Enter an integer: " int1
if [ $int1 -eq 0 ]
then
echo "Zero"
elif [ $int1 -lt 0 ]
then
echo "Negative"
else
if [ $((int1%2)) -eq 0 ]
then
echo "Even"
else
echo "Odd"
fi
fi이중 괄호 구문에 대한 산술 연산자:
Operator Usage/Description == Equal >= Greater Than or Equal > Greater Than <= Less Than or Equal < Less Than != Not Equal 이제 이전 스크립트를 재구성하고 이중 괄호 구문을 사용하겠습니다.
#!/bin/bash
read -p "Enter an integer: " int1
if (( $int1 == 0 ))
then
echo "Zero"
elif (( $int1 < 0 ))
then
echo "Negative"
else
if (( $((int1%2)) == 0 ))
then
echo "Even"
else
echo "Odd"
fi
fiSwitch 문
switch 문은 셸 스크립팅의 또 다른 종류의 조건문입니다. 이를 통해 프로그래머는 if 조건문에 비해 더 쉬운 방식으로 여러 값을 변수와 비교할 수 있습니다. switch 문의 구문은 다음과 같습니다.
casein
<pattern1>)
##series of code for pattern1
;;
<pattern2>)
##series of code for pattern2
;;
<patternN>)
##series of code for patternN
;;
*)
##default statements
esac
패턴은 변수의 가능한 값입니다. 각 패턴은 패턴의 break 문 역할을 하는 이중 세미콜론으로 구분됩니다. switch 문은 esac 문으로 닫힙니다.
#!/bin/bash
clear
read -p "Integer1: " int1
read -p "Integer2: " int2
echo "======================"
printf "Menu: \n[a] Addition\n[b]Subtraction\n[c]Multiplication\n[d]Division\n"
echo "======================"
read -p "Your choice: " choice
res=0
case $choice in
a)
res=$((int1+int2))
;;
b)
res=$((int1-int2))
;;
c)
res=$((int1*int2))
;;
d)
res=$((int1/int2))
;;
*)
echo "Invalid input"
esac
echo "The result is: " $res결론
bash 셸은 프로그래머에게 유용한 도구를 많이 제공합니다. 오늘날 대부분의 프로그래밍 언어와 마찬가지로 쉘 스크립트를 보다 대화식이고 스마트하게 만드는 조건부 결정을 내릴 수도 있습니다. 다음 시리즈에서는 반복적인 제어 구조를 다룰 예정입니다. 다음 시간까지.
참조
- http://www.gnu.org/software/bash/manual/html_node/Bash-Conditional-Expressions.html
다음 강의: 반복 제어 구조