24.07.2018 Views

Bash-Beginners-Guide

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

michel ~/test> cat leaptest.sh<br />

#!/bin/bash<br />

# This script will test if you have given a leap year or not.<br />

echo "Type the year that you want to check (4 digits), followed by [ENTER]:"<br />

read year<br />

<strong>Bash</strong> <strong>Guide</strong> for <strong>Beginners</strong><br />

if (( ("$year" % 400) == "0" )) || (( ("$year" % 4 == "0") && ("$year" % 100 !=<br />

"0") )); then<br />

echo "$year is a leap year."<br />

else<br />

echo "This is not a leap year."<br />

fi<br />

michel ~/test> leaptest.sh<br />

Type the year that you want to check (4 digits), followed by [ENTER]:<br />

2000<br />

2000 is a leap year.<br />

8.2.2. Prompting for user input<br />

The following example shows how you can use prompts to explain what the user should enter.<br />

michel ~/test> cat friends.sh<br />

#!/bin/bash<br />

# This is a program that keeps your address book up to date.<br />

friends="/var/tmp/michel/friends"<br />

echo "Hello, "$USER". This script will register you in Michel's friends database."<br />

echo -n "Enter your name and press [ENTER]: "<br />

read name<br />

echo -n "Enter your gender and press [ENTER]: "<br />

read -n 1 gender<br />

echo<br />

grep -i "$name" "$friends"<br />

if [ $? == 0 ]; then<br />

echo "You are already registered, quitting."<br />

exit 1<br />

elif [ "$gender" == "m" ]; then<br />

echo "You are added to Michel's friends list."<br />

exit 1<br />

else<br />

echo -n "How old are you? "<br />

read age<br />

if [ $age -lt 25 ]; then<br />

echo -n "Which colour of hair do you have? "<br />

read colour<br />

echo "$name $age $colour" >> "$friends"<br />

echo "You are added to Michel's friends list. Thank you so much!"<br />

else<br />

echo "You are added to Michel's friends list."<br />

exit 1<br />

fi<br />

fi<br />

Chapter 8. Writing interactive scripts 98

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!