Shell Script

계산기

1. 개요

쉘 스크립트의 간단한 구조를 살펴볼 수 있도록 만든 계산기.

 

2. Source code

#/bin/bash
 
PERMIT_USER="tuser"
LOG_LOC="/home/tuser/script/log.txt"
 
# check file $LOG_LOC - owner / directory / file / write permission
fileown=`stat -c "%U" $LOG_LOC`
if [ $fileown != $PERMIT_USER ]
    then rm -f $LOG_LOC
fi
if [ -d $LOG_LOC ]
    then rm -rf $LOG_LOC
    touch $LOG_LOC
elif [ ! -s $LOG_LOC ]
    then touch $LOG_LOC
fi
if [ ! -w $LOG_LOC ]
    then chmod u+w $LOG_LOC
fi
 
# log - date
echo -e "\nDATE : `date`" >> $LOG_LOC
 
# log - user
echo "USER : $USER" >> $LOG_LOC
if [ $USER != $PERMIT_USER ]
    then echo "ERROR : USER($USER)" >> $LOG_LOC
    exit
fi
 
clear
 
# menu print
echo "------------------------------------------"
echo "| Calculator                             |"
echo "------------------------------------------"
echo -e "| 1. +    2. -    3. *    4. /    5. all |" 
echo "------------------------------------------"
 
# input menu
echo -n "Choice : "
read CHOICE
# check input value
if [[ $CHOICE -lt 1 ]] || [[ $CHOICE -gt 5 ]]
    then echo "Choice ERROR!"
    echo "ERROR : Choice menu($CHOICE)" >> $LOG_LOC
    exit
fi
 
# input val1, val2
echo -en "\nINPUT1 : "
read INPUT1
echo -n "INPUT2 : "
read INPUT2
echo "INPUT1 : $INPUT1 / INPUT2 : $INPUT2" >> $LOG_LOC
 
# output result
echo "----------------- Result -----------------"
echo "----------------- Result -----------------" >> $LOG_LOC
if test $CHOICE -eq 1
    then echo "$INPUT1 + $INPUT2 =" `expr $INPUT1 + $INPUT2`
    echo "$INPUT1 + $INPUT2 =" `expr $INPUT1 + $INPUT2` >> $LOG_LOC
elif test $CHOICE -eq 2
    then echo "$INPUT1 - $INPUT2 =" `expr $INPUT1 - $INPUT2`
    echo "$INPUT1 - $INPUT2 =" `expr $INPUT1 - $INPUT2` >> $LOG_LOC
elif test $CHOICE -eq 3
    then echo "$INPUT1 * $INPUT2 =" `expr $INPUT1 \* $INPUT2`
    echo "$INPUT1 * $INPUT2 =" `expr $INPUT1 \* $INPUT2` >> $LOG_LOC
elif test $CHOICE -eq 4
    then echo "$INPUT1 / $INPUT2 =" `expr $INPUT1 \/ $INPUT2`
    echo "$INPUT1 / $INPUT2 =" `expr $INPUT1 \/ $INPUT2` >> $LOG_LOC
elif test $CHOICE -eq 5
    then echo "$INPUT1 + $INPUT2 =" `expr $INPUT1 + $INPUT2`
    echo "$INPUT1 - $INPUT2 =" `expr $INPUT1 - $INPUT2`
    echo "$INPUT1 * $INPUT2 =" `expr $INPUT1 \* $INPUT2`
    echo "$INPUT1 / $INPUT2 =" `expr $INPUT1 \/ $INPUT2`
 
    echo "$INPUT1 + $INPUT2 =" `expr $INPUT1 + $INPUT2` >> $LOG_LOC
    echo "$INPUT1 - $INPUT2 =" `expr $INPUT1 - $INPUT2` >> $LOG_LOC
    echo "$INPUT1 * $INPUT2 =" `expr $INPUT1 \* $INPUT2` >> $LOG_LOC
    echo "$INPUT1 / $INPUT2 =" `expr $INPUT1 \/ $INPUT2` >> $LOG_LOC
fi
 
echo "TIME : $SECONDS" >> $LOG_LOC

 

Back To Top