레이블이 Lang-Shell Script인 게시물을 표시합니다. 모든 게시물 표시
레이블이 Lang-Shell Script인 게시물을 표시합니다. 모든 게시물 표시

3/09/2016

Shell Script의 Sed 와 AWK (수정중)

1. Shell Script 기본예제 

기존보다 더 정리가 잘된 사이트를 찾음
  https://blog.gaerae.com/2015/01/bash-hello-world.html
  https://ryanstutorials.net/bash-scripting-tutorial/bash-if-statements.php

2. sed 기본사용

sed(stream editor) 약자이며, 흔히 Shell Script or vim에서 사용되는 교환 command이다.

문자열을 치환하거나 삭제할때 많이 사용되어지고 있다.
현재 간단히 테스트만 해보고 자세한 부분은 추후 시간이 될때 테스트해봐가면 익히자


$ vi test.sh 
#!/bin/bash

STR1="abc"
STR2="abc"
STR3="abc"

echo "Check STRING:  $STR1 $STR2 $STR3"
$ cp test.sh test1.sh

$ bash test.sh
Check STRING:  abc abc abc

$ sed -i 's/abc/def/g' test1.sh //  test.sh 파일에서 abc -> def 변환 한 후 저장 (미출력)
$ bash test1.sh
Check STRING:  def def def

$ sed 's/abc/def/g' test.sh   //  test.sh 파일에서 abc -> def 변환한 것을 화면에 출력만 하고 변경사항 test.sh 미저장 
#!/bin/bash

STR1="def"
STR2="def"
STR3="def"

echo "Check STRING:  $STR1 $STR2 $STR3"


관련링크 (설명이 잘되어있음)

  https://en.wikipedia.org/wiki/Sed
  http://vim.wikia.com/wiki/Search_and_replace
  http://milli.tistory.com/14

  https://www.shellscript.sh/variables2.html

3. awk 사용

Shell Script 혹은 명령어를 사용 도중에 특정 Column의 Row의 출력을 하고 싶을때 유용한것 같다
이밖에 다양한 기능이 있는 것 같은데, 좀 더 익숙해지면 익히자


$ df | awk 'NR == 2 {print $4}'    // NR Column , print $4 Row 
$ df | awk 'NR == 1 {print $4}'                         


관련링크 (설명)
  https://en.wikipedia.org/wiki/AWK
  https://www.gnu.org/software/gawk/manual/html_node/index.html#SEC_Contents
  http://ra2kstar.tistory.com/153
  http://www.thegeekstuff.com/2010/01/awk-tutorial-understand-awk-variables-with-3-practical-examples


2/27/2016

Linux RC Script 와 /etc/network/interfaces 분석

Linux Init Script로 배포하는 곳마다 다르며, 지속적으로 변화 중인 것 같아  간단히 기록한다.
아래와 같이 간단히 동작부분을 확인만 하자


#! /bin/sh
## 
# DIET-PC master initialisation script

# Copyright (C) 2002-2013 Paul A Whittaker 

# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

[ -f /etc/profile ] && . /etc/profile
export PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin
umask 022

notify ()
{
    # To aid degugging, you might wish to uncomment the sleep command, to give
    # you a chance to press the  key and see errors before they scroll
    # off.

    #busybox sleep 3
    echo -e "${HL_ON}$*${HL_OFF}"
    case "$HAVE_SPLASH" in
    TRUE)
## 숫자변수를 1씩 증가
 NOTIFY_COUNT=$(($NOTIFY_COUNT + 1))     
 echo "show $((65535 * $NOTIFY_COUNT / $NOTIFY_TOTAL))" >>/proc/splash
 ;;
    esac
}



busybox mount /proc
# If the console is a VT, we can use ANSI escapes to do highlighting.  "tty"
# doesn't work until /dev is mounted, so use console=xxx in /proc/cmdline to
# determine this.
case "`busybox sed -e 's/^.*\' /etc/rc /etc/rc.d/* /usr/etc/rc.d/* /usr/local/etc/rc.d/* | busybox wc -l`-1))
else
    HAVE_SPLASH=
fi
notify 'Mounting core filesystems'
ROOTDEV=`busybox sed -e 's/^.*\'; then
 # If root is read-only and it is not prohibited by a "no_root_union"
 # kernel parameter, try to mount a new root as a union of the original
 # (read-only) root filesystem and a tmpfs (read-write) filesystem.
 busybox mkdir -m 0755 /tmp/.overlay
 busybox modprobe -q unionfs
 busybox grep -qv '\' /proc/cmdline && busybox mount \
  -t unionfs -o dirs=/tmp/.overlay=rw:/=ro none /mnt
##
 if [ $? -eq 0 ]; then
     cd /mnt
     busybox pivot_root . ./oldroot
     busybox umount /oldroot/proc 2>/dev/null
     busybox mount /proc
 else
     # If not mounted already (via a kernel feature), mount a writable
     # tmpfs /dev.
     busybox awk 'BEGIN {n=0} $2 == "/dev" {n=1} END {exit n}' \
      /proc/mounts && busybox mount -t tmpfs -o \
      nr_blocks=256,nr_inodes=1024,mode=0755 none /dev
     # If the root filesystem is still read-only, try to remount it
     # read-write.  Remounts don't seem to work reliably when using the
     # Busybox mount applet, so only use it as a last resort.
            mount -o remount,rw / 2>/dev/null || busybox mount -o remount,rw /
     if [ $? -ne 0 ]; then
  # If still no-go, there is no point in continuing - let the
  # operator try to fix it and then reboot.
  echo 'Root filesystem is not writable, please fix!'
  [ "$LOCKDOWN" ] && busybox sleep 10 || busybox sulogin
  exec reboot -ifd
     fi
        fi
    fi
fi
busybox mount /sys 2>/dev/null
busybox mkdir -p /dev/pts
busybox mount /dev/pts 2>/dev/null
busybox mkdir -p /dev/shm
busybox mount /dev/shm 2>/dev/null

notify 'Initializing busybox'
busybox --install -s
# Remove any residual junk from /var/run.
rm -f /var/run/* 2>/dev/null

notify 'Initializing /dev'
ln -sf "$ROOTDEV" /dev/root 2>/dev/null
ln -snf /proc/self/fd /dev/fd
ln -sf /proc/self/fd/0 /dev/stdin
ln -sf /proc/self/fd/1 /dev/stdout
ln -sf /proc/self/fd/2 /dev/stderr
ln -sf /proc/kcore /dev/core
echo '/sbin/mdev' >/proc/sys/kernel/hotplug
mdev -s

if [ "$LOCKDOWN" ]; then
    # Remove root's password hash, thereby preventing root login and su to root.
    sed -i -e 's/^root:[^:]\+:/root:*:/' /etc/shadow
    # Turn off console login.
    sed -i -e '/^logn:/d' /etc/inittab
    kill -HUP 1
    # Set TCP wrappers to deny by default.
    echo 'ALL: ALL' >/etc/hosts.deny
    # Remove the setuid bit from busybox, to prevent use of setuid-root applets.
    chmod u-s /bin/busybox
    # Prevent unprivileged users from running an X11 terminal emulator.
    XTERM=`which xterm`
    [ "$XTERM" ] && chmod 700 "$XTERM"
fi

notify 'Initializing modules'
mkdir -p /lib/modules/`uname -r`
depmod -a
# If an eth0 hint has been provided via the boot loader or via
# /etc/modprobe.conf, use it now, in case there are multiple PCI NICs.
[ "$eth0" ] && modprobe -q `echo $eth0 | tr , ' '`
modprobe -q eth0
# Forceload some difficult modules that will otherwise neither coldplug nor
# hotplug.
modprobe -q parport
modprobe -q ppp
modprobe -q tun
modprobe -q floppy
modprobe -q loop
# Coldplug all platform, PCI, PCMCIA and USB devices initially found (in that
# order).
for BUS in platform pci pcmcia usb; do
    if [ -d /sys/bus/$BUS/devices ]; then
 notify "Initializing $BUS devices"
 cat /sys/bus/$BUS/devices/*/modalias 2>/dev/null | while read MODULE; \
  do
     modprobe -q $MODULE
 done
    fi
done
# Some last resorts, needed only in the event that bus coldplugging has not
# initialised the necessary device.
modprobe -q ide-generic
modprobe -q scsi_hostadapter
modprobe -q sound-slot-0
# Attempt to mount the legacy usb device filesystem if a USB host controller is
# now online.
mount /proc/bus/usb 2>/dev/null

# Set a provisional hostname.
if [ "`hostname`" = '(none)' ]; then
    # First try the contents of /etc/hostname, then the name of the special
    # non-localhost loopback address.
    HN=`cat /etc/hostname 2>/dev/null` || HN=`checkhostname -n 127.0.1.1`
    # Failing that, check all local MAC addresses against /etc/ethers.  If
    # there is a match, set the hostname from the hostname field of the first
    # matching entry.
    if [ $? -ne 0 -a -f /etc/ethers ]; then
 HN=`/sbin/ifconfig -a | awk 'BEGIN {printf "{IGNORECASE=1}\n"} \
  /HWaddr/ {printf "$1 == \"%s\" {print $2; exit}\n", $NF}' | \
  awk -f - /etc/ethers`
    fi
    # As a last resort, derive a hostname from the MAC address of a local
    # network interface.
    [ "$HN" ] || HN=`ifconfig -a | awk '/HWaddr/ {printf "X%s\n", $NF; exit}' \
     | tr -d :`
    # Use what we have.
    [ "$HN" ] && hostname "$HN"
fi

#### 
## 아래의 Shell script는 /etc/network를 자동으로 proc를 정보기반으로 생성해준다. 
## /etc/network 와 /etc/network/if-up.d 비롯하여 관련 directory  생성
## /proc/net/dev 정보를 바탕으로 IFACE (e.g eth0) 를 얻어 IFMETHOD 값을 설정 
## 
notify 'Initializing network'
mkdir -p /etc/network
(cd /etc/network; mkdir -p if-up.d if-down.d if-pre-up.d if-post-down.d)
if [ ! -f /etc/network/interfaces ]; then
    notify 'Network not configured - using DHCP'
    tail -n +3 /proc/net/dev | cut -f1 -d: | while read IFACE; do
 case "$IFACE" in
 lo)
     IFMETHOD='loopback'
     ;;
 sit*)
     IFMETHOD='manual'
     ;;
 *)
     IFMETHOD='dhcp'
     ;;
 esac
 echo "auto $IFACE" >>/etc/network/interfaces
 echo "iface $IFACE inet $IFMETHOD" >>/etc/network/interfaces
    done
fi
ifup -a
if [ -x /bin/ifplugd -a -x /etc/ifplugd/ifplugd.action ]; then
    for IFACE in `netstat -r | awk '/^[0-9]/ {print $NF}'`; do
 ifplugd -i "$IFACE" -p -q
    done
fi

if [ ! -s /etc/hosts.allow ]; then
    # In the absence of an explicit configuration, set TCP wrappers to grant
    # access to clients on any local subnet or with the same DNS domain name
    # suffix.
    ifconfig | grep '\>/etc/hosts.allow
 NETWORK=
 eval `ipcalc -n $ADDR 2>/dev/null`
 [ "$NETWORK" ] && echo "ALL: $NETWORK/$MASK" >>/etc/hosts.allow
    done
fi

# Check reverse lookups on all active non-loopback interfaces (now that we
# (possibly) have DNS).
HN=
for IPADDR in `ifconfig | grep 'inet addr:[0-9.]\+' | sed -e \
 's/^.*inet addr:\([0-9.]\+\).*$/\1/' | grep -v '^127\.'`; do
    HN=`checkhostname -n "$IPADDR" | cut -f1 -d.`
    [ "$HN" ] && break
done
if [ "$HN" ]; then
    # Any hostname found via reverse lookup will be considered more
    # authoritative than the provisional hostname (N.B. a hostname set by
    # /sbin/udhcpc-helper from DHCP results is provisional).  If you don't
    # want this behaviour, comment out everything except the "else" clause of
    # this "if" statement (including if, else, and fi lines).
    hostname "$HN"
else
    # If there is no better hostname, endorse the provisional one by adding
    # an /etc/hosts entry for it using a local IP address.
    sed -i -e '/\<'"`hostname`"\$/d /etc/hosts
    echo -e "${IPADDR:-127.0.1.1}\t`hostname`" >>/etc/hosts
fi

# If possible, set the system clock at this point.  Fsck needs this for
# scheduled checks, and loggers need it for meaningful timestamps.  Change -u
# to -l if you want your system clock to keep local time rather than UTC time.
# NTP synchronisation might be slow, but we can't background this, as it might
# be our last hope of getting a plausible clock setting (before fsck etc).
if [ -c /dev/rtc ]; then
    notify 'Setting time from hardware clock'
    if [ "`hwclock -u -r | egrep -w '(1970|2000)'`" ]; then
 notify 'Sanity check failed - ignoring data from hardware clock'
    else
 hwclock -u -s
    fi
    if checkhostname -q ${timeserver:-timeserver}; then
 notify 'Synchronising clock with network time server'
 ntpd -n -q -p ${timeserver:-timeserver}
 hwclock -u -w
 ntpd -p ${timeserver:-timeserver}
    fi
fi

notify 'Mounting all filesystems'
# We might have portmap (IPV4 only) or rpcbind (IPV4+IPV6) or neither.
portmap 2>/dev/null || rpcbind 2>/dev/null || true
# If you reference a network block device (/dev/nbd0 etc al) in /etc/fstab,
# you must prepare it for use here, e.g.
#nbd-client myserver 2000 /dev/nbd0 -persist >/dev/null 2>&1
# Scan for RAID arrays and try to assemble all that are found.  Only start
# fully intact arrays.
if [ "`which mdadm`" ]; then
    if [ ! -e /etc/mdadm.conf ]; then
 echo 'MAILADDR root' >/etc/mdadm.conf
 mdadm --examine --brief --scan --config=partitions >>/etc/mdadm.conf
    fi
    mdadm --assemble --scan --no-degraded --auto=yes
    mdadm --monitor --scan --daemonise --pid-file=/var/run/mdmonitor.pid
fi
# Scan for LVM volume groups and activate all that are found.
if [ "`which lvm`" ]; then
    rm -f /etc/lvm/cache/.cache
    lvm pvscan
    lvm vgscan
    lvm vgchange -ay
fi
fsck -aCRAT
case $? in
0|1)
    ;;
2|3)
    exec reboot -ifd
    ;;
*)
    echo 'Fsck failed ... need help!'
    [ "$LOCKDOWN" ] && sleep 10 || sulogin
    exec reboot -ifd
    ;;
esac
mount -a 2>/dev/null
if [ $? -ne 0 ]; then
    # The kernel might have been too slow to load the necessary modules during
    # the first attempt, so wait a moment and then retry.
    sleep 2
    mount -a 2>/dev/null
fi
swapon -a 2>/dev/null

# Logging chews up a little memory but is a valuable debugging aid.
notify 'Starting loggers'
if checkhostname -q ${logserver:-logserver}; then
    syslogd -m 0 -R ${logserver:-logserver}
else
    syslogd -m 0 -C
fi
klogd

# Start crond (if available).
if [ -x /sbin/crond ]; then
    notify 'Starting cron'
    mkdir -p /var/spool/cron/crontabs
    chmod 1733 /var/spool/cron/crontabs
    crond
fi

notify 'Starting power management'
# If CPU frequency scaling is available, install a demand-driven governor
# to reduce power consumption and heat output when high CPU performance is not
# needed.
for CPU in /sys/devices/system/cpu/cpu*; do
    if [ -f $CPU/cpufreq/scaling_governor ]; then
 echo 'conservative' >$CPU/cpufreq/scaling_governor 2>/dev/null
 if [ "`cat $CPU/cpufreq/scaling_governor`" != 'conservative' ]; then
     echo 'ondemand' >$CPU/cpufreq/scaling_governor 2>/dev/null
 fi
    fi
done
# Set a 30 minute idle spin-down on all hard disks.
for DISK in /dev/hd? /dev/sd?; do
    [ "$DISK" = 'hd?' -o "$DISK" = 'sd?' ] && continue
    hdparm -S 241 $DISK >/dev/null 2>&1
done

if [ -f /etc/sysctl.conf ]; then
    notify 'Adjusting kernel parameters'
    sysctl -e -p
fi


# If you want to force canonicalization of files in /usr/etc or /usr/local/etc,
# uncomment the following "if".  This will delete everything in /etc that
# previously got copied from /usr/etc and /usr/local/etc, and thereby force
# them to be copied again.  This is the only way to ensure that package removal
# doesn't leave config file remnants, but may prove very confusing to users,
# who will most likely expect the /etc copies to be authoritative and
# persistent.
#if [ -s /etc/shadowfiles ]; then
#    (
#    cd /etc
#    sed -e "s/'/'\"'\"'/g" -e "s/^/rm -f '/" -e "s/\$/'/" shadowfiles | sh
#    )
#fi
# Since packages installed in /usr and /usr/local can't directly own files in
# /etc, we will non-destructively merge /usr/etc and /usr/local/etc into /etc.
# If the root filesystem is persistent or has a persistent layer, pre-existing
# copies in /etc will supercede the installation defaults in /usr[/etc].
# Otherwise, changes will be lost when the system is rebooted, and permanent
# changes can only occur by modifiying the /usr/[local/]etc master copies.
for PKG_ROOT in /usr /usr/local; do
    if [ -d $PKG_ROOT/etc ]; then
 (
 cd $PKG_ROOT/etc
 find . -type f -print
 find . -print | cpio -d -p /etc 2>/dev/null
 )
    fi
done > /etc/shadowfiles

# Initialise optional packages.
#
# Rather than executing rc.d files (which would have significant fork and exec
# overheads), we source them and run the functions and/or aliases they define.
# This is fast, but also fragile, because a syntax error in any rc.d file will
# kill this script.  On a persistent root filesystem, we have no way of knowing
# whether or not configure actions have already occurred, so the rc.d scripts
# must be "replay-safe" and should avoid unnecessary reconfiguration.
ls /etc/rc.d | while read SVC; do
    . /etc/rc.d/$SVC
    eval ${SVC}_configure
    logger -t 'rc' -p daemon.info "$SVC configured"
    eval ${SVC}_start
    logger -t 'rc' -p daemon.info "$SVC started"
done

# Display an active interface summary just before the login prompt appears, so
# that the IP address(es) in use remain visible on the console as long as
# possible.
ifconfig | awk 'BEGIN {i=""} $0 !~ /^[[:blank:]]/ && $0 != "" {i=$1}
 $2 ~ /^addr:/ {print i; print $0}'

[ "$HAVE_SPLASH" ] && echo 'show 65535' >>/proc/splash




  http://dietpc.org/downloads/source/common/diet-pc/initscript/etc/rc

4/10/2015

Bash Shell 예제들

  
반드시 참조 아래사이트 
  https://wiki.kldp.org/HOWTO/html/Adv-Bash-Scr-HOWTO/
  https://ahyuo79.blogspot.com/2014/01/awk.html

$ cat reset_lte.sh
#!/bin/sh
#
# Usage examples:
#       ./reset_lte.sh stop
#       ./reset_lte.sh start



VER=1.6

LTE_PWR=160
LTE_EN=161

WAIT_100MS() {
    sleep 0.1
}

WAIT_10MS() {
    sleep 0.01
}

WAIT_1S() {
    sleep 1
}

enable_lte() {
    echo "ENABLE/RESET LTE  (LTE_PWR:$LTE_PWR, LTE_EN:$LTE_EN)"
    # write output (Power)
    echo "0" > /sys/class/gpio/gpio$LTE_EN/value; WAIT_100MS
    echo "1" > /sys/class/gpio/gpio$LTE_EN/value
    # Reset (LTE_IGT)
    echo "1" > /sys/class/gpio/gpio$LTE_PWR/value
}

disable_lte() {
    echo "DISABLE/RESET LTE  (LTE_PWR:$LTE_PWR, LTE_EN:$LTE_EN)"
    # write output (Power)
    echo "0" > /sys/class/gpio/gpio$LTE_EN/value; WAIT_100MS  
    # off (LTE_IGT) 
    echo "0" > /sys/class/gpio/gpio$LTE_PWR/value    
}

case "$1" in
    start)
    enable_lte
    ;;
    stop)    
    disable_lte
    ;;
    *)
    echo "Usage: $0 {start|stop} "
    exit 1
    ;;
esac

exit 0


$ cat reset_lte.sh
#!/bin/sh
# Setup LDO/RESET Service (systemd) 
# 


WAIT_100MS() {
    sleep 0.1
}

echo "   " | logger -t pwr_setup -p local0.notice
echo "   " | logger -t pwr_setup -p local0.notice
echo "   " | logger -t pwr_setup -p local0.notice
echo "Setup ALL POWER SYSTEM (LDO/RESET) Start !!!!! " | logger -t pwr_setup -p local0.notice

/usr/bin/setup_gpio.sh enable | logger -t pwr_setup -p local0.notice

if [ $? -eq 0 ]
then
  echo "Success: setup_gpio.sh enable (Setup GPIO about LDO/RESET)" | logger -t pwr_setup -p local0.notice
else
  echo "Failure: setup_gpio.sh enable (Setup GPIO about LDO/RESET)" >&2 | logger -t pwr_setup -p local0.notice
  exit 1
fi

/usr/bin/reset_gps.sh start | logger -t gps_reset -p local0.notice

if [ $? -eq 0 ]
then
  echo "Success: reset_gps.sh start (GPS RESET OK)" | logger -t gps_reset -p local0.notice
else
  echo "Failure: reset_gps.sh start (GPS RESET Failed) " >&2 | logger -t gps_reset -p local0.notice
  exit 1
fi


/usr/bin/reset_lte.sh start | logger -t lte_reset -p local0.notice

if [ $? -eq 0 ]
then
  echo "Success: reset_lte.sh start (LTE RESET OK)" | logger -t lte_reset -p local0.notice
else
  echo "Failure: reset_lte.sh start (LTE RESET Failed)" >&2 | logger -t lte_reset -p local0.notice
  exit 1
fi


exit 0


$ cat /etc/syslog.conf
#  /etc/syslog.conf     Configuration file for busybox's syslogd utility
#
#  Author: Jeonghun lee


local0.notice       /var/log/test1

local1.notice       /var/log/test2

# others  /var/log/message






1/05/2014

Bash Shell Script 기본작성

1. Bash Shell Script 기본

간단한 TEST Program을 만들거나, Service를 구동할때 자주 접하는것이 Bash Shell Script이며, 이를 이용하여 좀 더 복잡한 Program 도 작성가능하다.

이런 부분을 간략하게 정리하며, 관련된 TIP들을 정리한다.

  • Bash or Shell Script 기본 테스트 
Shell Script에 맨 위에 본인이 사용하는 Shell의 종류를 넣어주고 반드시 실행권한

$ sh -version  // 기본 Shell을 bash로 사용한다면 bash로 나옴 
// bin/sh 이 없다면, ->dash or bash Link로 기본 Shell 설정 
or
$ bash -version 

$ vi  test0.sh  // bin/sh ->dash or bash로 실행 (기본 Shell) 
#!/bin/sh
echo "Hello!! Shell Script"

$ vi  test1.sh  // /bin/bash로 실행
#!/bin/bash
echo "Hello!! Shell Script"

$ vi watch.sh  // /bin/bash로 실행 process 감시
#!/bin/bash
watch "ps aux | sort -nrk 3,3 | head -n 20"

watch
  https://linux.die.net/man/1/watch
sort
head

$ chmod +x test0.sh test1.sh  //실행권한 
$ sh ./test0.sh     // sh를 이용하여 new process 실행
$ bash ./test1.sh   // bash를 이용하여 new process 실행 
or 
$ ./test0.sh    // current process에서 실행 
$ ./test1.sh    // current process에서 실행 


Bash 시작부분
  https://wiki.kldp.org/HOWTO/html/Adv-Bash-Scr-HOWTO/sha-bang.html


  • 고급 Bash Shell Script Guide (반드시 숙지 및 참조)
각각의 세부 Bash Shell Script Guide는 아래의사이트를 참조하자
  https://wiki.kldp.org/HOWTO/html/Adv-Bash-Scr-HOWTO/


1.1 Bash Shell script 의 조건문 다양한 예제 

  • 일반적인 변수사용과 if문사용

$ vi iftest1.sh
#!/bin/sh
# 주석 
# bash가 지원되며 아래와 같이 맨위에 설정 
#!/bin/bash


STR1="Hello!!-ShellScript" 
STR2="Hello!!-Others"
TEST="OK"

#
# 변수의 사용법 
#
echo $STR1
echo ${STR2} 

#
## if 문 예제 STRING 
#
if [ $STR1 == $STR1 ]
then      
	echo "TEST IF ${TEST} "
elif [ $STR1 == $STR2 ]
then
	echo "TEST ELIF ${TEST}"
else
	echo "TEST ELSE ${TEST}"
fi
exit 0

  • 조건식 및 File 체크 

! EXPRESSION	The EXPRESSION is false.
-n STRING	The length of STRING is greater than zero.
-z STRING	The lengh of STRING is zero (ie it is empty).
STRING1 = STRING2	STRING1 is equal to STRING2
STRING1 != STRING2	STRING1 is not equal to STRING2
INTEGER1 -eq INTEGER2	INTEGER1 is numerically equal to INTEGER2
INTEGER1 -gt INTEGER2	INTEGER1 is numerically greater than INTEGER2
INTEGER1 -lt INTEGER2	INTEGER1 is numerically less than INTEGER2
-d FILE	FILE exists and is a directory.
-e FILE	FILE exists.
-r FILE	FILE exists and the read permission is granted.
-s FILE	FILE exists and it's size is greater than zero (ie. it is not empty).
-w FILE	FILE exists and the write permission is granted.
-x FILE	FILE exists and the execute permission is granted.

조건문 IF 문의 EXPRESSION

[ -z ${A} ] : A 문자열의 길이가 0이면 TRUE
[ -n ${A} ] : A 문자열의 길이가 0이 아니면 TRUE
[ ${A} -eq ${B} ] : A와 B값이 같으면 TRUE
[ ${A} -ne ${B} ] : A와 B값이 다르면 TRUE
[ ${A} -gt ${B} ] : A가 B보다 크면 TRUE
[ ${A} -ge ${B} ] : A가 B보다 크거나 같으면 TRUE
[ ${A} -lt ${B} ] : A가 B보다 작으면 TRUE
[ ${A} -le ${B} ] : A가 B보다 작거나 같으면 TRUE

[ 조건식A -a 조건식B ] : 조건식 A와 B가 모두 TRUE이면 TRUE (&& 와 동일)
[ 조건식A -o 조건식B ] : 조건식 A가 TRUE거나 조건식B가 TRUE면 TRUE (|| 와 동일)

조건문 IF 문의 FILE 관련 EXPRESSION A 
[ !${A}   ] : A 파일이 디렉토리면 TRUE
[ -d ${A} ] : A 파일이 디렉토리면 TRUE
[ -e ${A} ] : A 파일이(노드, 디렉토리, 소켓 등등 모두) 존재하면 TRUE
[ -L ${A} ] : A 파일이 심볼릭 링크면 TRUE
[ -r ${A} ] : A 파일이 읽기 가능하면 TRUE
[ -s ${A} ] : A 파일의 크기가 0 보다 크면 TRUE
[ -w ${A} ] : A 파일이 쓰기 가능하면 TRUE
[ -x ${A} ] : A 파일이 실행 가능하면 TRUE
[ -c ${A} ] : A 파일이 Special character file 이면 TRUE
[ -f ${A} ] : A 파일이 디렉토리가 아닌 일반 regular 파일이면 TRUE
[ -S ${A} ] : A 파일이 소켓이면 TRUE

[ ${A} -nt ${B} ] : A 파일 B 파일보다 최신파일이면 참
[ ${A} -ot ${B} ]  : A 파일이 B 파일보다 이전파일이면 참
[ ${A} -ef ${B} ] : A 파일과 B 파일이 같은 파일이면 참

IF문 다양한예제

내부변수

특수변수


  • if 문에 and 연산과 or 연산 추가 
$ vi iftest2.sh
#!/bin/sh
# Author: Jeonghun 

ETH0_OP=`ifconfig | grep eth0 | awk '{print $1}'`
ETH1_OP=`ifconfig | grep eth1 | awk '{print $1}'`

if [ $ETH0_OP == "eth0" ] && [ $ETH1_OP == "eth1" ]
then 
	echo -e "\x1b[1;93m Both of them $ETH0_OP ,$ETH1_OP   \x1b[0m" 
elif [ $ETH0_OP == "eth0" ] || [ $ETH1_OP == "eth1" ]
then 
	echo -e "\x1b[1;93m Either of them $ETH0_OP , $ETH1_OP   \x1b[0m"
else
	echo -e "\x1b[1;93m The other $ETH0_OP , $ETH1_OP   \x1b[0m"
fi

exit 0


expr 과 문자열 조작 예제
  https://wiki.kldp.org/HOWTO/html/Adv-Bash-Scr-HOWTO/string-manipulation.html

unary operator expected 문제 
쿼트문제 
  https://devstein.tistory.com/17


1.2 Bash 의 Function 구현 및 다양한 예제  

  • Count 증가시키는 Function 구현

$ vi test2.sh
#!/bin/bash
#   for function example 
#

count=$(( ${count}+1 ))

CNT=0

set_count()
{
     echo "CNT=$((CNT+1))"    
}

while [ $CNT -le 5 ]; do
   set_count
done


  • Sleep이용하여 Trigger Function 예제 (RANDOM사용)
$ cat sensoraging.sh 
#!/bin/bash
#
# for doing test by using GPIO,  not Senors  
# 
# $ vi ./sensorinit.sh
# echo "out" >  /sys/class/gpio/gpio388/direction
#
# $ vi /etc/rc.local 
# sudo -s /home/nvidia/deep_alpr/darknet/sensoraging.sh
#

export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
LOG_DIR=$HOME/deep_alpr/darknet
cd $LOG_DIR

## J21 Header 
#0 J21-PIN31 (GPIO9_MOTION) GPIO298 -> IRQ366  (FDV30IN FET, Level Shift)
#3 J21-PIN37 (GPIO26)       GPIO388 -> IRQ199  (FDV30IN FET, Level Shift) only test 

TSLEEP=0
FUNCNT=0
LOG=./log/sensoraging_$(date +%Y%m%d-%H%M-%S).log

set_trigger() {
   # for LOG
   TIME=$(date "+%Y-%m-%d %H:%M:%S")  
   echo "TIME=$TIME"   >> $1
   echo "ACTIVE HIGH"  >> $1
   echo "FUNCTION: $2 CNT $3 " >> $1
   echo "TOTAL SLEEP: $TSLEEP" >> $1
   echo "" >> $1
   
   TSLEEP=0

   # Active High
   echo 1 > /sys/class/gpio/gpio388/value
   # 1~4 second (sensor dealy)
   DELAY=`echo $(( RANDOM % (3 + 1 ) + 1 ))`
   sleep $DELAY
   echo 0 > /sys/class/gpio/gpio388/value

}

short_time() {
    # 1 ~ 9 , try count 
    FUNCNT=`echo $(( RANDOM % (8 + 1 ) + 1 ))`

    while [ $FUNCNT -gt 0 ]
       do 
          set_trigger $1 "short_time" $FUNCNT
    
          # 0 ~ 2 , try count 
          SET_SLP=`echo $(( RANDOM % (2 + 1 ) + 0 ))`

          if   [ $SET_SLP -eq 0 ]; then    
             # RANDOM 1~3 second
             RSLEEP=`echo $(( RANDOM % (2 + 1 ) + 1 ))`

          elif [ $SET_SLP -eq 1 ]; then
             # RANDOM 3~5
             RSLEEP=`echo $(( RANDOM % (2 + 1 ) + 3 ))`

          else
             # RANDOM 4~14
             RSLEEP=`echo $(( RANDOM % (10 + 1 ) + 4 ))`
          fi

          TSLEEP=$(($TSLEEP+$RSLEEP))
          sleep $RSLEEP
          FUNCNT=$(($FUNCNT-1))

       done

}


long_time() {
    # 1 ~ 4 , try count 
    FUNCNT=`echo $(( RANDOM % (3 + 1 ) + 1 ))`

    while [ $FUNCNT -gt 0 ]
       do
          set_trigger $1 "long_time" $FUNCNT

          # 0 ~ 2 , try count 
          SET_SLP=`echo $(( RANDOM % (2 + 1 ) + 0 ))`

          if   [ $SET_SLP -eq 0 ]; then
             # RANDOM 15~135 second
             RSLEEP=`echo $(( RANDOM % (120 + 1 ) + 15 ))`

          elif [ $SET_SLP -eq 1 ]; then
             # RANDOM 120~180
             RSLEEP=`echo $(( RANDOM % (60 + 1 ) + 120 ))`

          else
             # RANDOM 180~240
             RSLEEP=`echo $(( RANDOM % (60 + 1 ) + 180 ))`
          fi

          TSLEEP=$(($TSLEEP+$RSLEEP))
          sleep $RSLEEP
          FUNCNT=$(($FUNCNT-1))

       done

}

verylong_time() {
    # 1 ~ 3 , try count 
    FUNCNT=`echo $(( RANDOM % (2 + 1 ) + 1 ))`

    while [ $FUNCNT -gt 0 ]
       do
          set_trigger $1 "verylong_time" $FUNCNT

          # 0 ~ 2 , try count 
          SET_SLP=`echo $(( RANDOM % (2 + 1 ) + 0 ))`

          if   [ $SET_SLP -eq 0 ]; then
             # RANDOM 200~260 second
             RSLEEP=`echo $(( RANDOM % (60 + 1 ) + 200 ))`

          elif [ $SET_SLP -eq 1 ]; then
             # RANDOM 600~660
             RSLEEP=`echo $(( RANDOM % (60 + 1 ) + 600 ))`

          else
             # RANDOM 900~960
             RSLEEP=`echo $(( RANDOM % (60 + 1 ) + 900 ))`
          fi

          TSLEEP=$(($TSLEEP+$RSLEEP))
          sleep $RSLEEP
          FUNCNT=$(($FUNCNT-1))

       done

}

# Simple 
test_modeA() {

while [ 1 ]
  do
    set_trigger $LOG "simple" 0
    # RANDOM 1~6
    RSLEEP=`echo $(( RANDOM % (5 + 1 ) + 1 ))`
    sleep $RSLEEP
    TSLEEP=$(($TSLEEP+$RSLEEP))
  done
}


# Complex 
test_modeB() {

while [ 1 ]
  do
    # 0 ~ 2 select 
    FSEL=`echo $(( RANDOM % (2 + 1 ) + 0 ))`

    if [ $FSEL -eq 0 ]; then
       short_time $LOG 
    elif [ $FSEL -eq 1 ]; then
       long_time $LOG 
    else
       verylong_time $LOG
    fi

  done
} 

#SET 0 for ACTIVE HIGH
echo 0 > /sys/class/gpio/gpio388/value
sleep 1

#simple
test_modeA
#complex
#test_modeB


  • Interrupt 확인 후 Count 진행 

$ cat powercheck.sh
#!/bin/bash
# for checking Power Button and Power Monitor Chip 
#
export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
LOG_DIR=$HOME/deep_alpr/darknet
cd $LOG_DIR

check_time() {
   time=$(date "+%Y-%m-%d %H:%M:%S")
   echo $time >> $1
   echo "" >> $1   
   return 
} 

check_powerINT() {

   EX_PINT=$PINT   
   PINT=`cat /proc/irq/380/spurious | awk 'NR == 1 {print $2}'` 
   echo "- POWER_INT=$PINT" >> $1
   echo "" >> $1

   if [ $CNT -gt 1 ]; then
       if [ $PINT -ne $EX_PINT ]; then
            time=$(date "+%Y-%m-%d %H:%M:%S")
            echo " TIME = $time " >> $2
            echo " COUNT=$CNT" >> $2
            echo " - POWER_INT= $EX_PINT , $PINT" >> $2
       fi
   fi
}

CNT=0
LOG=./log/power_$(date +%Y%m%d-%H%M-%S).log
LOG_INT=./log/power_$(date +%Y%m%d-%H%M-%S)_int.log
LOG_CHG=./log/power_$(date +%Y%m%d-%H%M-%S)_chg.log

while [ 1 ]
  do 
    echo "COUNT=$CNT" >> $LOG       
    check_time  $LOG 
    check_powerINT $LOG $LOG_INT
    CNT=$(($CNT+1))
    sleep 1
  done



  • RANDOM 사용하는 예제 

$ cat sensoraging.sh
#!/bin/bash
#
# for doing test by using GPIO,  not Senors  
# 
# $RANDOM  Shell에서 RANDOM값 제공 
# if 

export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
LOG_DIR=$HOME/deep_alpr/darknet
cd $LOG_DIR

## J21 Header 
#0 J21-PIN31 (GPIO9_MOTION) GPIO298 -> IRQ366  (FDV30IN FET, Level Shift)
#3 J21-PIN37 (GPIO26)       GPIO388 -> IRQ199  (FDV30IN FET, Level Shift) only test 
TSLEEP=0
FUNCNT=0
LOG=./log/sensoraging_$(date +%Y%m%d-%H%M-%S).log

set_trigger() {
   # for LOG
   TIME=$(date "+%Y-%m-%d %H:%M:%S")  
   echo "TIME=$TIME"   >> $1
   echo "ACTIVE HIGH"  >> $1
   echo "FUNCTION: $2 CNT $3 " >> $1
   echo "TOTAL SLEEP: $TSLEEP" >> $1
   echo "" >> $1
   TSLEEP=0

   # Active High
   echo 1 > /sys/class/gpio/gpio388/value
   # 1~4 second (sensor dealy)

   DELAY=`echo $(( RANDOM % (3 + 1 ) + 1 ))`
   sleep $DELAY
   echo 0 > /sys/class/gpio/gpio388/value

}

short_time() {

    # 1 ~ 9 , try count 
    FUNCNT=`echo $(( RANDOM % (8 + 1 ) + 1 ))`

    while [ $FUNCNT -gt 0 ]
       do 
          set_trigger $1 "short_time" $FUNCNT
  
          # 0 ~ 2 , try count 
          SET_SLP=`echo $(( RANDOM % (2 + 1 ) + 0 ))`
          if   [ $SET_SLP -eq 0 ]; then    
             # RANDOM 1~3 second
             RSLEEP=`echo $(( RANDOM % (2 + 1 ) + 1 ))`
          elif [ $SET_SLP -eq 1 ]; then
             # RANDOM 3~5
             RSLEEP=`echo $(( RANDOM % (2 + 1 ) + 3 ))`
          else
             # RANDOM 4~14
             RSLEEP=`echo $(( RANDOM % (10 + 1 ) + 4 ))`
          fi
          TSLEEP=$(($TSLEEP+$RSLEEP))
          sleep $RSLEEP
          FUNCNT=$(($FUNCNT-1))
       done

}

long_time() {

    # 1 ~ 4 , try count 
    FUNCNT=`echo $(( RANDOM % (3 + 1 ) + 1 ))`

    while [ $FUNCNT -gt 0 ]

       do
          set_trigger $1 "long_time" $FUNCNT
          # 0 ~ 2 , try count 
          SET_SLP=`echo $(( RANDOM % (2 + 1 ) + 0 ))`

          if   [ $SET_SLP -eq 0 ]; then
             # RANDOM 15~135 second
             RSLEEP=`echo $(( RANDOM % (120 + 1 ) + 15 ))`
          elif [ $SET_SLP -eq 1 ]; then
             # RANDOM 120~180
             RSLEEP=`echo $(( RANDOM % (60 + 1 ) + 120 ))`
          else
             # RANDOM 180~240
             RSLEEP=`echo $(( RANDOM % (60 + 1 ) + 180 ))`
          fi

          TSLEEP=$(($TSLEEP+$RSLEEP))
          sleep $RSLEEP
          FUNCNT=$(($FUNCNT-1))
       done

}

verylong_time() {

    # 1 ~ 3 , try count 
    FUNCNT=`echo $(( RANDOM % (2 + 1 ) + 1 ))`

    while [ $FUNCNT -gt 0 ]
       do
          set_trigger $1 "verylong_time" $FUNCNT
          # 0 ~ 2 , try count 
          SET_SLP=`echo $(( RANDOM % (2 + 1 ) + 0 ))`

          if   [ $SET_SLP -eq 0 ]; then
             # RANDOM 200~260 second
             RSLEEP=`echo $(( RANDOM % (60 + 1 ) + 200 ))`
          elif [ $SET_SLP -eq 1 ]; then
             # RANDOM 600~660
             RSLEEP=`echo $(( RANDOM % (60 + 1 ) + 600 ))`
          else
             # RANDOM 900~960
             RSLEEP=`echo $(( RANDOM % (60 + 1 ) + 900 ))`
          fi
          TSLEEP=$(($TSLEEP+$RSLEEP))
          sleep $RSLEEP
          FUNCNT=$(($FUNCNT-1))
       done

}

# Simple 

test_modeA() {

while [ 1 ]
  do
    set_trigger $LOG "simple" 0
    # RANDOM 1~6
    RSLEEP=`echo $(( RANDOM % (5 + 1 ) + 1 ))`
    sleep $RSLEEP
    TSLEEP=$(($TSLEEP+$RSLEEP))
  done

}

test_modeB() {

while [ 1 ]
  do
    # 0 ~ 2 select 
    FSEL=`echo $(( RANDOM % (2 + 1 ) + 0 ))`
    if [ $FSEL -eq 0 ]; then
       short_time $LOG 
    elif [ $FSEL -eq 1 ]; then
       long_time $LOG 
    else
       verylong_time $LOG
    fi
  done

} 

#SET 0 for ACTIVE HIGH
echo 0 > /sys/class/gpio/gpio388/value
sleep 1

# select following one of two modes 
#Simple Mode
test_modeA

#Complex Mode
#test_modeB



  • awk 와 같이 사용하는 예제
awk를 이용하여 쉽게 각 proc와 sys의 정보를 얻어온 후 이 기반으로 이를 체크 
$ cat sensorcheck.sh
#!/bin/bash
#

export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
LOG_DIR=$HOME/deep_alpr/darknet
cd $LOG_DIR

check_sensorINT() {
   EX_SINT0=$SINT0   
   EX_SINT1=$SINT1  
   EX_SINT2=$SINT2  
   EX_SINT3=$SINT3  

## J21 Header 
#0 J21-PIN31 (GPIO9_MOTION) GPIO298 -> IRQ366  (FDV30IN FET , Level Shift)
#1 J21-PIN33 (GPIO11_AP)    GPIO389 -> IRQ200  (TXB0108 , Level Shift) 
#2 J21-PIN13 (GPIO_PE6)     GPIO397 -> IRQ208  (TXB0108 , Level Shift) 
#3 J21-PIN37 (GPIO26)       GPIO388 -> IRQ199  (FDV30IN FET, Level Shift) only test 

   SINT0=`cat /proc/irq/366/spurious | awk 'NR == 1 {print $2}'` 
   SINT1=`cat /proc/irq/200/spurious | awk 'NR == 1 {print $2}'` 
   SINT2=`cat /proc/irq/208/spurious | awk 'NR == 1 {print $2}'` 
   SINT3=`cat /proc/irq/199/spurious | awk 'NR == 1 {print $2}'` 
   PINVAL0=`cat /sys/class/gpio/gpio298/value`
   PINVAL1=`cat /sys/class/gpio/gpio389/value`
   PINVAL2=`cat /sys/class/gpio/gpio397/value`
   PINVAL3=`cat /sys/class/gpio/gpio388/value`

#   echo "- PIN31_INT=$SINT0" >> $1
#   echo "- PIN33_INT=$SINT1" >> $1
#   echo "- PIN13_INT=$SINT2" >> $1
#   echo "" >> $1

#### 
#$? 이전에 실행했던 return 값 
#$0 Shell Script name  
#$1 1st ARG
#$2 2nd ARG 
#$3 3rd ARG 
#

   if [ $CNT -gt 1 ]; then

       SINTDIFF0=$(($SINT0-$EX_SINT0))
       SINTDIFF1=$(($SINT1-$EX_SINT1))
       SINTDIFF2=$(($SINT2-$EX_SINT2))
       SINTDIFF3=$(($SINT3-$EX_SINT3))
       time=$(date "+%Y-%m-%d %H%M%S")

       if [ $SINT0 -ne $EX_SINT0 ]; then
            if [ $SINTCNT0 -gt 1 ]; then
               CNTDIFF0=$(($CNT-$EX_CNT0))  

            fi

            echo " TIME = $time " >> $2
            echo " PCNT31=$SINTCNT0  SEC_CNT=$CNT SEC_DIFF=$CNTDIFF0" >> $2
            echo " - PIN31_INT0= ($SINTDIFF0) $EX_SINT0 -> $SINT0" >> $2
            echo " - PIN31_VAL0= $PINVAL0" >> $2

            

            #J21-PIN31 active High

            if [ $PINVAL0 == "1"  ]; then

               echo " - INTERRUPT_PIN31=$PINTCNT0" >> $2
               echo " - TIME = $time " >> $3
               echo " - INTERRUPT_PIN31=$PINTCNT0" >> $3
               echo "" >> $3
               PINTCNT0=$(($PINTCNT0+1))
            fi

            echo "" >> $2
            SINTCNT0=$(($SINTCNT0+1))
            EX_CNT0=$CNT

       fi

       if [ $SINT1 -ne $EX_SINT1 ]; then

            if [ $SINTCNT1 -gt 1 ]; then
               CNTDIFF1=$(($CNT-$EX_CNT1))  
            fi
          
            echo " TIME = $time " >> $2
            echo " PCNT33=$SINTCNT1  SEC_CNT=$CNT SEC_DIFF=$CNTDIFF1 " >> $2
            echo " - PIN33_INT1= ($SINTDIFF1) $EX_SINT1 -> $SINT1" >> $2
            echo " - PIN33_VAL1= $PINVAL1" >> $2
            echo "" >> $2
            SINTCNT1=$(($SINTCNT1+1))
            EX_CNT1=$CNT

       fi

# 
# if -ne 
# 
       if [ $SINT2 -ne $EX_SINT2 ]; then
            if [ $SINTCNT2 -gt 1 ]; then
               CNTDIFF2=$(($CNT-$EX_CNT2))  
            fi
            echo " TIME = $time " >> $2
            echo " PCNT13=$SINTCNT2  SEC_CNT=$CNT SEC_DIFF=$CNTDIFF2 " >> $2
            echo " - PIN13_INT2= ($SINTDIFF2) $EX_SINT2 -> $SINT2" >> $2
            echo " - PIN13_VAL2= $PINVAL2" >> $2
            echo "" >> $2
            SINTCNT2=$(($SINTCNT2+1))
            EX_CNT2=$CNT

       fi

       if [ $SINT3 -ne $EX_SINT3 ]; then
            if [ $SINTCNT3 -gt 1 ]; then
               CNTDIFF3=$(($CNT-$EX_CNT3))
            fi
            echo " TIME = $time " >> $2
            echo " PCNT37=$SINTCNT3  SEC_CNT=$CNT SEC_DIFF=$CNTDIFF3 " >> $2
            echo " - PIN37_INT3= ($SINTDIFF3) $EX_SINT3 -> $SINT3" >> $2
            echo " - PIN37_VAL3= $PINVAL3" >> $2
            echo " - TIME = $time " >> $3
            echo " - 2ND_PIN37_VAL=$PINVAL3" >> $3
            echo "" >> $3

            if [ $PINVAL3 == "0"  ]; then
               echo " - INTERRUPT_PIN37=$PINTCNT3" >> $2
               PINTCNT3=$(($PINTCNT3+1))
            fi

            echo "" >> $2
            SINTCNT3=$(($SINTCNT3+1))
            EX_CNT3=$CNT

       fi

   fi

}

CNTDIFF0=0
CNTDIFF1=0
CNTDIFF2=0
CNTDIFF3=0
SINTCNT0=0
SINTCNT1=0
SINTCNT2=0
SINTCNT3=0
PINTCNT0=0
PINTCNT1=0
PINTCNT2=0
PINTCNT3=0
CNT=0
LOG=./log/sensor_$(date +%Y%m%d-%H%M-%S).log
LOG_INT=./log/sensor_$(date +%Y%m%d-%H%M-%S)_int.log
LOG_INT0=./log/sensor_$(date +%Y%m%d-%H%M-%S)_int0.log
time=$(date "+%Y-%m-%d %H:%M:%S")
echo $time >> $LOG

while [ 1 ]
  do 
    #echo "COUNT=$CNT" >> $LOG
    #time=$(date "+%Y-%m-%d %H:%M:%S")
    #echo $time >> $LOG
    #echo "" >> $LOG
    check_sensorINT $LOG $LOG_INT $LOG_INT0 
    CNT=$(($CNT+1))
    sleep 1
  done