Crmgo Блог

Приклади If then Else

Приклади If then Else

Вкладені інструкції if Всередині інструкції if ви можете використовувати ще одну інструкцію if . Ви можете користуватися такою кількістю рівнів вкладеності інструкцій if , з якою впораєтеся. У цьому прикладі перевіряються високосні роки:

Приклади If then Else

 

anny /etc/cron.daily> cat disktest.sh
#!/bin/bash

# This script does a very simple test for checking disk space.

space=`df -h | awk '{print $5}' | grep % | grep -v Use | sort -n | tail -1 | cut -d "%" -f1 -`
alertvalue="80"

if [ "$space" -ge "$alertvalue" ]; then
  echo "At least one of my disks is nearly full!" | mail -s "daily diskcheck" root
else
  echo "Disk space normal" | mail -s "daily diskcheck" root
fi

Вкладені інструкції if

Усередині інструкції if ви можете використовувати ще одну інструкцію if. Ви можете користуватися такою кількістю рівнів вкладеності інструкцій if, з якою впораєтеся.

У цьому прикладі перевіряються високосні роки:

anny ~/testdir> cat testleap.sh
#!/bin/bash
# This script will test if we're in a leap year or not.

year=`date +%Y`

if [ $[$year % 400] -eq "0" ]; then
  echo "This is a leap year.  February has 29 days."
elif [ $[$year % 4] -eq 0 ]; then
        if [ $[$year % 100] -ne 0 ]; then
          echo "This is a leap year, February has 29 days."
        else
          echo "This is not a leap year.  February has 28 days."
        fi
else
  echo "This is not a leap year.  February has 28 days."
fi

anny ~/testdir> date
Tue Jan 14 20:37:55 CET 2003

anny ~/testdir> testleap.sh
This is not a leap year.

Примітка: матеріал міг бути створений за підтримки ШІ з подальшою людською редакцією. Відповідальний за зміст: Dmytro Lomaka, Kaltenkirchen.

Рубрики: bash