Run The Bridge
shell-script로 계산기 만들기 본문
0. 들어가기에 앞서
shell script 강의가 끝났다.
이를 활용해서 계산기를 만들어본다.
윈도우에서 제공하는 계산기는 숫자, 입력 기호, 숫자를 입력하는 형식이다.
우리가 작성하는 스크립트도 다음과 같이 무한입력을 받는 방식으로 짜 본다.
1. 체크리스트 작성
- 사용자의 입력을 받는다.
- 사용자한테 사칙연산 기호를 입력받는다.
- 사용자의 입력을 다시 받는다.
- 계산 결과를 출력한다.
- 계속 계산 유무를 입력받는다.
5-1. 계속 계산: 사용자의 입력을 받고 사칙연산 기호의 입력도 받는다.
5-2. 계산 중단: 계산결과를 출력하고 계산기를 중단한다. - 끝
2. 계산기 작성
우선 calc.sh라는 파일을 만든다.
vi calc.sh
chmod +x calc.sh
---
작업을 하다가 블로그 글이 모두 날아갔다.
현재 사용자의 입력, 사칙연산 입력, 사용자의 두 번째 입력까지 받는 스크립트를 작성했다.
아래와 같다.
#!/bin/bash
read -p "Please put in the numbers: " user_input
#echo $user_input
echo "+, -, /, * Please enter one of them."
read -p "Please put in the operation: " user_operation
while true; do
if [[ $user_operation != '+' ]] && [[ $user_operation != '-' ]] && [[ $user_operation != '*' ]] && [[ $user_operation != '/' ]] ; then
echo -e "Repeat plz"\n
read -p "Please put in the operation: " user_operation
else
#echo $user_operation
break
fi
done
read -p "Please put in the second numbers: " user_second_input
echo "first: ${user_input}"
echo "second: ${user_operation}"
echo "thrid: ${user_second_input}"
---
입력 결과는 다음과 같다. 이제 본격적으로 계산해본다.
3. 계산
쉘 스크립트에서 계산식은 $(($ 기호 $))로 이루어진다.
다음의 사이트를 참고하면 손쉽게 쉘 스크립트 연산에 대해 알 수 있다.(물론 내 블로그에도 포스팅되어있음!)
https://codechacha.com/ko/shell-script-add-minus-multi-division/
간단하게 마지막에 echo문을 추가하면 된다.
echo $(($user_input $user_operation $user_second_input))
root@kube-master /opt/project- # ./calc.sh
Please put in the numbers: 25
+, -, /, * Please enter one of them.
Please put in the operation: +
Please put in the second numbers: 25
first: 25
second: +
thrid: 25
50
4. 무한 반복
이제 계산을 얼추 했으니... 사용자가 원할 때까지 입력을 계속 받아본다.
그전에.. 최종 값을 계속 저장하면서 호출해야 되므로 결괏값의 마지막은 result에 담아둔다.
result=$(($user_input $user_operation $user_second_input))
echo "result: $result"
---
현재 반복까지 구현하고, 사용자 입력에 따라 계속 진행할지, 말지를 선택한다.
그 과정에서 터미널 창이 지저분해 보여서 clear를 써주었다.
약간 코드가 복잡하다.
근데 구조는 if, while문 반복이라 생각보다 쉽다.
또한 for문이나, case문을 사용하지 않았다.
사용자 입력에서 Yy/Nn 방식으로 case문을 사용하고 싶었는데...
명령문이 너무 길어서 초장부터 쓰지 않아서 중간에 넣기에는 내가 실력이 부족하다!
#!/bin/bash
flag=0
result=0
while true
do
read -p "Would you like to go on [Y/N]: " response
echo ""
if [[ $response =~ ^[Yy]$ ]]
then
clear
if [[ $flag == 0 ]]
then
read -p "Please put in the numbers: " user_input
echo ""
fi
echo "Current value is $result"
echo ""
echo "+, -, /, * Please enter one of them."
read -p "Please put in the operation: " user_operation
echo ""
while true; do
if [[ $user_operation != '+' ]] && [[ $user_operation != '-' ]] && [[ $user_operation != '*' ]] && [[ $user_operation != '/' ]] ; then
echo -e "Repeat plz"\n
read -p "Please put in the operation: " user_operation
else
#echo $user_operation
break
fi
done
read -p "Please put in the second numbers: " user_second_input
echo ""
if [[ $flag == 0 ]]
then
result=$(($user_input $user_operation $user_second_input))
echo "result: $result"
else
result=$(($result $user_operation $user_second_input))
echo "result: $result"
fi
flag=1
elif [[ $response =~ ^[Nn]$ ]]
then
echo $result
break
else
echo "Please add the correct value."
sleep 2
clear
fi
done
5. 예외처리
이제 계산기에서 예외처리를 해줘야 한다.
내가 생각하는 예외처리는 일단은.... 나머지를 나눌 때 0으로 나누는 에러를 처리해줘야 한다.
추가로 내 계산기는 소수점 계산이 안 되는 int형이다.. 이 부분은 위의 과정을 처리하고 한 번 고민해봐야겠다.
'/'를 입력했을 때, if문 조건을 달면 돼서 생각보다 금방 할 수 있다.
#!/bin/bash
flag=0
result=0
while true
do
read -p "Would you like to go on [Y/N]: " response
if [[ $response =~ ^[Yy]$ ]]
then
clear
if [[ $flag == 0 ]]
then
read -p "Please put in the numbers: " user_input
echo ""
fi
echo "Current value is $result"
echo ""
echo "+, -, /, * Please enter one of them."
read -p "Please put in the operation: " user_operation
echo ""
while true; do
if [[ $user_operation != '+' ]] && [[ $user_operation != '-' ]] && [[ $user_operation != '*' ]] && [[ $user_operation != '/' ]] ; then
echo -e "Repeat plz"\n
read -p "Please put in the operation: " user_operation
else
#echo $user_operation
break
fi
done
while true
do
read -p "Please put in the second numbers: " user_second_input
if [[ $user_operation == '/' ]] && [[ $user_second_input == 0 ]]; then
echo "Zero division Error"
sleep 1
clear
else
break
fi
done
if [[ $flag == 0 ]]
then
result=$(($user_input $user_operation $user_second_input))
echo "result: $result"
else
result=$(($result $user_operation $user_second_input))
echo "result: $result"
fi
flag=1
elif [[ $response =~ ^[Nn]$ ]]
then
echo "result: $result"
break
else
echo "Please add the correct value."
sleep 2
clear
fi
done
중간에 while true문을 사용해서 user_second_input 값에 대해 검증을 시도한다.
'/'와 '0'이 들어오면 Zero division Error를 출력하고, 사용자의 입력을 다시 받는다.
만약 0이 아니면 pass 시키면 돼서 break를 넣어 while문을 중단시킨다.
6. 소수점 계산
해주세요!
만들어줘!
나에게 가르침을 줘!! 주세요!!
7. 결과
아직 부족한 게 많다...
그래도 계산기부터 시작해서 차근차근 하나씩 파이썬, C로 만들었던 것들을 한 번 짜 보자..!!
https://github.com/anfrhrl5555/shellscript_calculator
감사합니다.
'Cloud > Linux' 카테고리의 다른 글
package의 의존성 파일 출력 및 설치 (1) | 2022.02.22 |
---|---|
Ansible-playbook, 숫자 입력만으로 원하는 곳 실행하기 (0) | 2022.02.16 |
shell script master -9- (마지막) (0) | 2022.01.27 |
shell script master -8- (0) | 2022.01.27 |
shell script master -7- (0) | 2022.01.27 |