A function gives back two kinds of result:
| You want | The function | The caller |
|---|---|---|
| Yes or no | return 0 (yes) or return 1 (no) | if is_sunday "$day"; then |
| A value | Prints it, and nothing else | time=$(opens_at south) |
bash
is_sunday() {
if [ "$1" = "sun" ]; then
return 0
fi
return 1
}
opens_at() {
grep "^$1," ~/hours.txt | cut -d, -f2
}
for day in sun mon; do
if is_sunday "$day"; then
echo "$day: closed"
else
time=$(opens_at south)
echo "$day: $time"
fi
donetext
sun: closed ← is_sunday sun returned 0
mon: 07:30 ← time holds what opens_at printedIn a function, use return, not exit: exit ends the whole script.
~/price.sh writes each item you give it, from ~/menu.txt (one item,price per line).
- Run
./price.sh latte pie scone. It stops atpie. Inis_on_menu, change the line that ends the whole script so it ends only the function. - Below
is_on_menu, defineprice_of, which prints only the price of the item it is given. - In the loop, catch the price with
$( ), and write it in place ofon the menu.
Objectives
- Check every item, even after one that is not on the menu.
price_ofprints only the price../price.sh latte pie "carrot cake"writes each price.