99 Bottles of Beer/Shell

From Rosetta Code
Revision as of 03:50, 21 November 2014 by rosettacode>Hajo (moving code from main task-page to sub-page)

Task in Shell(s)

99 Bottles of Beer/Shell is part of 99 Bottles of Beer. You may find other members of 99 Bottles of Beer at Category:99 Bottles of Beer.

99 Bottles of Beer done in any of the Shell-languages.

Batch File

<lang dos>@echo off setlocal

main

for /L %%i in (99,-1,1) do ( call :verse %%i ) echo no bottles of beer on the wall echo no bottles of beer echo go to the store and buy some more echo 99 bottles of beer on the wall echo. set /p q="Keep drinking? " if %q% == y goto main if %q% == Y goto main goto :eof

verse

call :plural %1 res echo %res% of beer on the wall echo %res% of beer call :oneit %1 res echo take %res% down and pass it round set /a c=%1-1 call :plural %c% res echo %res% of beer on the wall echo. goto :eof

plural

if %1 gtr 1 goto :gtr if %1 equ 1 goto :equ set %2=no bottles goto :eof

gtr

set %2=%1 bottles goto :eof

equ

set %2=1 bottle goto :eof

oneit

if %1 equ 1 ( set %2=it ) else ( set %2=one ) goto :eof</lang>


UNIX Shell

Works with: Bourne Shell

<lang bash>#!/bin/sh

i=99 s=s

while [ $i -gt 0 ]; do

       echo "$i bottle$s of beer on the wall"
       echo "$i bottle$s of beer

Take one down, pass it around"

       # POSIX allows for $(( i - 1 )) but some older Unices didn't have that
       i=`expr $i - 1`

[ $i -eq 1 ] && s= || s=s

       echo "$i bottle$s of beer on the wall

" done</lang>

Works with: Bash
Works with: ksh93
Works with: zsh

<lang bash>bottles() {

 beer=$1
 [ $((beer)) -gt 0 ] && echo -n $beer ||  echo -n "No more"
 echo -n " bottle"
 [ $((beer)) -ne 1 ] && echo -n "s"
 echo -n " of beer"

}

for ((i=99;i>=0;i--)); do

 ((remaining=i))
 echo "$(bottles $remaining) on the wall"
 echo "$(bottles $remaining)"
 if [ $((remaining)) -eq 0 ]; then
   echo "Go to the store and buy some more"
   ((remaining+=99))
 else
   echo "Take one down, pass it around"
   ((remaining--))
 fi
 echo "$(bottles $remaining) on the wall"
 echo

done</lang>

C Shell

See 99 Bottles of Beer/Shell <lang csh>@ i=99 set s=s while ($i > 0) echo "$i bottle$s of beer on the wall" echo "$i bottle$s of beer" echo "Take one down, pass it around" @ i = $i - 1 if ($i == 1) then set s= else set s=s endif echo "$i bottle$s of beer on the wall" echo "" end</lang>