While (Bash Newbies)

From UCLUG

Jump to: navigation, search

Contents

Overview

These are the scripts and notes from September 9, 2008's Bash Shell Scripting for Newbies session. The topic is while and the rest of Bash's compound statements.

Example 1: whileSpinner

Text of whileSpinner:

#!/bin/bash

# New: arrays
spinner[0]=-
spinner[1]=/
spinner[2]='|'
spinner[3]=\\

n=0

echo -n " "
# new: while
while true
do
       n=$[n + 1]
       n=$((n % 4))
       echo -en "\b${spinner[$n]}"
       #sleep 1
done

format of while

Format of the while compound statement:

while some_commands
do
    some_more_commands
done

or:

while command; do block; done

more info on test

For the program test (and [ ]), see man test.

For the Bash builtin test (and [[ ]]), see man builtin and help test.

more info on &&

&& ...

Example 2: whileMenu

Text of whileMenu:

#!/bin/bash

menu() {
       echo "1) Check email"
       echo "2) Surf web"
       echo "3) Edit file"
       echo "4) Spreadsheet"
       echo "5) Exit"
}

menu
while read -p "Enter an option: [1-5] " a
do
       echo
       # New: case
       case $a in
               1)
                       echo mutt
                       ;;
               one)    echo gmail
                       ;;
               2|ff)
                       echo firefox ;;
               "3"|'4')        echo openoffice
                       ;;
               v)      echo vim;;
        j*|J*|*rox*|????)
            echo Yes, Jas rox, but anyway...
            ;;
               '*')    echo exit
                       ;;
               *)      exit
                       ;;
       esac
       echo
       menu
done

format of case

Format of the case compound statement:

case $variable in  list_of_things 
    something)
        statements
        ;;
    whatever)
        more_statements
        ;;
    whatevers)
        ...
        ;;
esac

info on globs/wildcards

For more info on globs or wildcards, see man 7 glob and man bash, section "Pattern Matching"

Example 3: whileMenu2

#!/bin/bash

# Similar menu program, using `select'

PS3="Type in a number: "

# New: until
#while true
until ! true
do
       # New: select
       select proggy in mutt gmail firefox openoffice vim exit
       do
               [[ exit == $proggy ]] && exit
               echo
               echo Executing $proggy ...
               #$proggy
               break
       done
       echo
done

format of until

until commands
do
    block
done

format of select

select a_variable in a_list
do
    block
done

Example 4: whileReadStats

#!/bin/bash

echo Products:
# pipe to while
sort -n < stats |
       while read a b
       do
               echo "$a x $b = $[ a * b]"
       done

echo Remainders:
# redirect while
while read c d; do
       echo "$c mod $d = $[c % d ]"
done < stats

File: stats

23 878
243 3
423 43
4 54
342 0
2 78
2 1
23 32
3 326
3 1221
2 98000