Crmgo Blog

Przykłady If then Else

Przykłady If then Else

Instrukcje if zagnieżdżone Wewnątrz instrukcji if możesz użyć kolejnej instrukcji if. Możesz stosować tyle poziomów zagnieżdżenia instrukcji if, na ile Cię stać. W tym przykładzie sprawdzane są lata przestępne:

Przykłady 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

Zagnieżdżone instrukcje if

Wewnątrz instrukcji if możesz użyć kolejnej instrukcji if. Możesz stosować tyle poziomów zagnieżdżenia instrukcji if, na ile Cię stać.

W tym przykładzie sprawdzane są lata przestępne:

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.

Uwaga: wpis mógł powstać z pomocą AI i redakcji. Odpowiedzialny: Dmytro Lomaka, Kaltenkirchen.