[SLUG] If there's a competition for the most useless bash script...

Jonathan Worthington jonathan at jwcs.net
Tue Apr 22 23:34:01 BST 2003


Hi,

> I've just tried your script.  Works well with one exception.  I can't get
it to
> use any symbol other than the default #.  I copied and pasted your script
so
> it shouldn't be because of a typo.  Any ideas?
Yeah, I've just checked it myself now and it was throwing a nasty error at
me...so something wrong.  I honestly don't know how I missed that, but then
maybe it had to do with the fact that it was written at 1 AM.  Anyway, my
fix...

> # If no char is entered set it to default (#).
> if [ -n $CHAR ]; then
>      CHAR='#'
> fi

You can probably guess the error is there.  The -n (Null) check doesn't seem
to want to work...  Ah well, we can always do it by checking number of
arguments...  Replace the above with:-

# If no char is entered set it to default (#).
if [ $# -lt 3 ]; then
     CHAR='#'
fi

And it appears to behave.  :-)  We should also probably do a check for if
there aren't enough arguments passed too.  So here's the ammended version
that I've just retested.

#!/bin/bash

# Rectangle drawing script.  Takes three parameters:-
#  ./rectangle.sh length width chracater
# Where character is the character used to print the rectangle.
# #####################################################################

# If there are less than 2 arguments, blow up.
if [ $# -lt 2 ]; then
 echo "Not enough arguments!"
 exit
fi

# Assign input.
LENGTH=$1
WIDTH=$2
CHAR=$3

# If no char is entered set it to default (#).
if [ $# -lt 3 ]; then
 CHAR='#'
fi

# Print a blank line.
echo

# Draw rectangle.
CURWID=0
while [ $CURWID -lt $WIDTH ]; do
 CURLEN=0
 while [ $CURLEN -lt $LENGTH ]; do
  printf "$CHAR"
  CURLEN=$((++CURLEN))
 done
 printf "\n"
 CURWID=$((++CURWID))
done

# Print area.
printf "\nThe area of the rectangle is $[WIDTH*LENGTH].\n\n"
###

Anyone know of a better way to get out with an error than exit?  In Perl we
can die "Message"; and that should go to STDOUT, but die doesn't work in
Bash.  exit does because shell scripts run in their own instance of the
shell.  (Or to the best of my knowledge.  That's why they inherit
environment variables and the likes, because it's really just a fork system
call, and also when they crash they don't take your shell with them!)

Jonathan





More information about the Scarborough mailing list