I created it as a small story of Bash programming. Let's display the pyramid using "*".
#!/bin/bash
echo "*"
echo "**"
echo "***"
echo "****"
echo "*****"
$ ./pyramid.sh
*
**
***
****
*****
The program I mentioned earlier is a good program. However, it is inflexible, so we will modify it to let the user specify the number of steps.
#!/bin/bash
ast='*'
echo -n "Input number => "
read num
for i in $(seq 1 $num)
do
echo "$ast"
ast='*'${ast}
done
You can use the counter with while instead of for. I chose for because it is more readable than while.
$ ./pyramid.sh
Input number => 6
*
**
***
****
*****
******
It was quite difficult. There is a space to the left of the "*", so how do you handle it? In addition, it is necessary to reduce the blanks one by one.
$ cat center_pyramid.sh
#!/bin/bash
ast='*'
spc=' '
echo -n "Input number => "
read num
(( spc_cnt = $num - 2 ))
for i in $(seq 1 $spc_cnt)
do
spc=' '${spc}
done
for j in $(seq 1 $num)
do
echo "$spc""$ast"
ast='**'${ast}
spc=${spc#' '}
done
I used string substitution for variables as a way to remove whitespace.
$ ./center_pyramid.sh
Input number => 6
*
***
*****
*******
*********
***********
By creating this program
--Branch syntax --Repeating syntax --read command --test command --Handling of symbols with special meaning --Variable string replacement --Bash's manners
I understand.
Recommended Posts