#!/bin/zsh -f ############################################################################# # # cm2ft # # This shell script converts centimeters to feet and inches. # # Written & Copyright by Christian J. Robinson June 2010 # You may copy/use this under the terms of the GNU General Public License, # version 2 or later. # # Requirements: # - The "units" utility. (Not any more.) # # Assumptions: # - That the user only wants to convert whole centimeters, and not fractions # of centimeters (no decimal point is allowed). # # Bugs: # - None known, but despite the simplicity of the script at least one # probably exists. # # TODO: # - Allow a less terse output mode with a command-line switch? # - Allow a strictly numeric output mode that excludes the input for use in # other scripts? # ############################################################################# # # $Log: cm2ft,v $ # Revision 1.5 2010/06/09 01:59:43 infynity # *** empty log message *** # # Revision 1.4 2010/06/06 00:44:04 Heptite # Allow long/short output, and input in meters # # Revision 1.3 2010/06/04 05:29:55 Heptite # Change code so it no longer requires the units utility # ############################################################################# # Init some variables: BASENAME="${0##*/}" let cm_ft=30.48 let in_ft=12 readonly BASENAME cm_ft cm_in # Functions: usage() { local where exitval where="2" exitval=1 [[ "$1" == "-h" || "$1" == "--help" ]] && where=1 && exitval=0 cat <<-EOF >&$where Usage: $BASENAME [options] centimeters Where "centimeters" is a positive integer number, and can be specified in meters with a trailing "m" modifier. Options: -l, --long Use "long" output. -s, --short Use "short"/terse output. -h, --help Show this help and exit. Examples: % $BASENAME 100 1m = 3' 3.37" % $BASENAME -l 1m 1 meter = 3 feet 3.37 inches % $BASENAME -s 1m 3 3.37 EOF exit $exitval } # Parse command line options: output=0 [[ $1 == '-l' || $1 == '--long' ]] && output=1 && shift [[ $1 == '-s' || $1 == '--short' ]] && output=2 && shift [[ $#* != 1 || ( $1 != <1-> && $1 != <1->m && $1 != <1->meters ) ]] && usage $* # Compute: if [[ $1 == <1->m* ]] then let cm=${${(s:m:)1}[1]} cm=$((cm * 100)) else let cm=$1 fi let ft=$(( cm / cm_ft )) let in=.${${(s:.:)ft}[2]} let in=$(( in * in_ft )) if [[ $cm -ge 100 ]] then m=$(printf '%.2f' $(( cm / 100.0 ))) [[ $m == *.00 ]] && m=$m[1,-4] fi # Format and print: if [[ "$output" == 1 ]] then if [[ ! -z "$m" ]] then [[ $m -ne 1 ]] && plural='s' m="${m} meter$plural" else [[ $cm -ne 1 ]] && plural='s' m="${cm} centimeter$plural" fi f=$(printf '%i' $ft) [[ $f -eq 1 ]] && plural='foot' || plural='feet' f="$f $plural" [[ $in -eq 1 ]] && plural='' || plural='es' i=$(printf "%.2f inch$plural" $in) echo "$m equals $f and $i" elif [[ "$output" == 2 ]] then f=$(printf "%i" $ft) i=$(printf '%.2f' $in) echo "$f $i" else [[ ! -z "$m" ]] && m="${m}m" || m="${cm}cm" f=$(printf "%i'" $ft) i=$(printf '%.2f"' $in) echo "$m = $f $i" fi