[LINUX] Shell program to display pyramids

Introduction

I created it as a small story of Bash programming. Let's display the pyramid using "*".

Five-tiered pyramid to the left

Source

#!/bin/bash

echo "*"
echo "**"
echo "***"
echo "****"
echo "*****"

Execution result

$ ./pyramid.sh
*
**
***
****
*****

Pyramid that displays the specified number of steps

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.

Source

#!/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.

Execution result

$ ./pyramid.sh
Input number => 6
*
**
***
****
*****
******

Pyramid that displays the specified number of steps (centered version)

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.

Source

$ 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.

Execution result

$ ./center_pyramid.sh
Input number => 6
     *
    ***
   *****
  *******
 *********
***********

in conclusion

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

Shell program to display pyramids
Shell program to display multiplication tables
Sample program to display video with PyQt
Program to weaken Japanese
How to run a Python program from within a shell script
Shell to create django project
How to start the program
I tried to create Bulls and Cows with a shell program
[Rails] How to display Google Map
Program to convert Japanese to station name
I made a program to input what I ate and display calories and sugar