Baza wiedzy NASutilsNieoficjalnaEnglish

Bash · lekcja 13 z 30 · Dane, funkcje i wiersz poleceńZwróć kod

return ustawia kod, który czyta if i $?.

Programowanie na NAS-ie › Bash w 30 lekcjach

13-return.sh Pobierz 13-return.sh

#!/usr/app/TurboShell/bin/bash
# return ustawia kod wyjścia funkcji, więc if może go sprawdzić
is_number() {
  [[ $1 =~ ^-?[0-9]+$ ]]
}

level() {
  local used=$1
  ((used < 80)) && return 0
  ((used < 95)) && return 1
  return 2
}

for used in 75 93 97 dużo; do
  if ! is_number "$used"; then
    echo "$used: to nie liczba"
    continue
  fi
  level "$used"
  echo "$used: poziom $?"
done

Terminal

$ bash 13-return.sh
75: poziom 0
93: poziom 1
97: poziom 2
dużo: to nie liczba

Ćwiczenie

Napisz is_weekend: czy podany dzień to sobota albo niedziela.