drawing a shape with shell script
I'm trying to draw a tree in the following form
Code:
*
***
*****
*******
*********
as you can see I need both spaces, and "*" stars in every line, but I can't get it quite the way I want
Code:
#!/bin/bash
display_tree() {
local rows=$1
local columns=$2
for ((i=0; i<$rows; i++))
do
#spaces loop
for ((j=0; j<$columns; j++))
do
echo -n " "
#drawing tree loop
for ((a=0; a<$(($i + 1)); a++))
do
echo -n "*"
done
done
echo
done
}
if [ $# -eq 2 ]; then
display_tree $1 $2
else
echo "Usage: $0 rows columns"
fi
Re: drawing a shape with shell script
Code:
$ n=6; row="";
$ for(( i=0; i<n; i++ )); do row="$row "; done; row="${row%?}*"; for(( i=0; i<n; i++ )); do echo "$row"; row="${row#?}**"; done
*
***
*****
*******
*********
***********
Re: drawing a shape with shell script
Quote:
Originally Posted by
Vaphell
Code:
$ n=6; row="";
$ for(( i=0; i<n; i++ )); do row="$row "; done; row="${row%?}*"; for(( i=0; i<n; i++ )); do echo "$row"; row="${row#?}**"; done
*
***
*****
*******
*********
***********
great job!.. would you mind explaining this two sentences
Code:
row="${row%?}*"
row="${row#?}**"
I know it is a variable declaration, but what's on the right side of "=" sign I haven't seen it yet
Re: drawing a shape with shell script
Code:
$ x="abcd"
$ echo ${x#?} ${x%?}
bcd abc
these parameter expansions trim chunks that match given pattern from the left (#) and from the right (%). ? symbol used here means 'single character'
first loop generates n spaces long string.
${row%?}* trims the rightmost char and adds * (last space replaced by *)
i get 1st row that way
note that (n+1)-th row has -1 space and +2 stars when compared to n-th row so in each iteration of the second loop i kill one space on the left, and add 2 *s on the right: ${row#?}**
Re: drawing a shape with shell script
Quote:
Originally Posted by
Vaphell
Code:
$ x="abcd"
$ echo ${x#?} ${x%?}
bcd abc
these parameter expansions trim chunks that match given
pattern from the left (#) and from the right (%). ? symbol used here means 'single character'
first loop generates n spaces long string.
${row%?}* trims the rightmost char and adds * (last space replaced by *)
i get 1st row that way
note that (n+1)-th row has -1 space and +2 stars when compared to n-th row so in each iteration of the second loop i kill one space on the left, and add 2 *s on the right:
${row#?}**
very efficient algorithm!..
Thanks