Читаем Сценарии командной оболочки. Linux, OS X и Unix. 2-е издание полностью

····echo "$0: cannot write in your home directory ($HOME)" >&2

····exit 1

··fi

··echo "Agenda: The Unix Reminder Service"

··/bin/echo −n "Date of event (day mon, day month year, or dayname): "

··read word1 word2 word3 junk

··if isDayName $word1; then

····if [! -z "$word2"]; then

······echo "Bad dayname format: just specify the day name by itself." >&2

······exit 1

····fi

····date="$(normalize $word1)"

··else

····if [-z "$word2"]; then

······echo "Bad dayname format: unknown day name specified" >&2

······exit 1

····fi

····if [! -z "$(echo $word1|sed 's/[[: digit: ]]//g')"]; then

······echo "Bad date format: please specify day first, by day number" >&2

········exit 1

····fi

····if ["$word1" −lt 1 −o "$word1" −gt 31]; then

······echo "Bad date format: day number can only be in range 1-31" >&2

······exit 1

····fi

····if [! isMonthName $word2]; then

······echo "Bad date format: unknown month name specified." >&2

······exit 1

····fi

····word2="$(normalize $word2)"

····if [-z "$word3"]; then

······date="$word1$word2"

····else

······if [! -z "$(echo $word3|sed 's/[[: digit: ]]//g')"]; then

········echo "Bad date format: third field should be year." >&2

········exit 1

······elif [$word3 −lt 2000 −o $word3 −gt 2500]; then

········echo "Bad date format: year value should be 2000–2500" >&2

········exit 1

······fi

······date="$word1$word2$word3"

····fi

··fi

··/bin/echo −n "One-line description: "

··read description

··# Данные готовы к записи в файл

··echo "$(echo $date|sed 's/ //g')|$description" >> $agendafile

··exit 0

Второй сценарий, в листинге 3.13, короче, но используется чаще.

Листинг 3.13. Сценарий agenda, сопутствующий сценарию addagenda из листинга 3.12

··#!/bin/sh

··# agenda — сканирует файл. agenda в поисках записей, относящихся

··#·· к текущей дате

··agendafile="$HOME/.agenda"

··checkDate()

··{

····# Создать значения по умолчанию для сопоставления с текущей датой.

····weekday=$1 day=$2 month=$3 year=$4

····format1="$weekday" format2="$day$month" format3="$day$month$year"

····# И выполнить поиск среди записей в файле…

····IFS="|" # Команда read автоматически разбивает

············#·· прочитанные строки по символам в IFS.

····echo "On the agenda for today: "

····while read date description; do

······if ["$date" = "$format1" −o "$date" = "$format2" −o \

·········· "$date" = "$format3"]

······then

········echo " $description"

······fi

····done < $agendafile

··}

··if [! -e $agendafile]; then

····echo "$0: You don't seem to have an.agenda file. " >&2

····echo "To remedy this, please use 'addagenda' to add events" >&2

····exit 1

··fi

··# Получить текущую дату…

Перейти на страницу:

Все книги серии Для профессионалов

Сценарии командной оболочки. Linux, OS X и Unix. 2-е издание
Сценарии командной оболочки. Linux, OS X и Unix. 2-е издание

Сценарии командной оболочки помогают системным администраторам и программистам автоматизировать рутинные задачи с тех самых пор, как появились первые компьютеры. С момента выхода первого издания этой книги в 2004 году многое изменилось, однако командная оболочка bash только упрочила свои лидирующие позиции. Поэтому умение использовать все ее возможности становится насущной необходимостью для системных администраторов, инженеров и энтузиастов. В этой книге описываются типичные проблемы, с которыми можно столкнуться, например, при сборке программного обеспечения или координации действий других программ. А решения даются так, что их легко можно взять за основу и экстраполировать на другие схожие задачи.Цель этой книги — продемонстрировать практические приемы программирования сценариев на bash и познакомить с самыми распространенными утилитами на коротких и компактных примерах, не вдаваясь в излишние подробности. Экспериментируйте с этими сценариями — ломайте, исправляйте и приспосабливайте их под свои нужды, чтобы понять, как они работают. Только так вы сможете решать самые сложные задачи.

Брендон Перри , Дейв Тейлор

Программирование, программы, базы данных

Похожие книги

C++ Primer Plus
C++ Primer Plus

C++ Primer Plus is a carefully crafted, complete tutorial on one of the most significant and widely used programming languages today. An accessible and easy-to-use self-study guide, this book is appropriate for both serious students of programming as well as developers already proficient in other languages.The sixth edition of C++ Primer Plus has been updated and expanded to cover the latest developments in C++, including a detailed look at the new C++11 standard.Author and educator Stephen Prata has created an introduction to C++ that is instructive, clear, and insightful. Fundamental programming concepts are explained along with details of the C++ language. Many short, practical examples illustrate just one or two concepts at a time, encouraging readers to master new topics by immediately putting them to use.Review questions and programming exercises at the end of each chapter help readers zero in on the most critical information and digest the most difficult concepts.In C++ Primer Plus, you'll find depth, breadth, and a variety of teaching techniques and tools to enhance your learning:• A new detailed chapter on the changes and additional capabilities introduced in the C++11 standard• Complete, integrated discussion of both basic C language and additional C++ features• Clear guidance about when and why to use a feature• Hands-on learning with concise and simple examples that develop your understanding a concept or two at a time• Hundreds of practical sample programs• Review questions and programming exercises at the end of each chapter to test your understanding• Coverage of generic C++ gives you the greatest possible flexibility• Teaches the ISO standard, including discussions of templates, the Standard Template Library, the string class, exceptions, RTTI, and namespaces

Стивен Прата

Программирование, программы, базы данных