编写Shell程序,一个小程序。

2025-01-08 10:58:22
推荐回答(2个)
回答1:

代码如下:

#!/bin/bash
             
echo -n "how many lines do you want to display?"
read nLines
for ((i=1; i<=nLines; i++))
do
      for ((j=1; j<=$nLines-$i; j++))
      do
              echo -n ' '
      done
                  
      for ((h=1; h<=$((2*$i-1)); h++))
      do
              echo -n '*'
      done
      echo ' '
done

结果为

$ sh test.sh
how many lines do you want to display?5
    *
   ***
  *****
 *******
*********
$ sh test.sh
how many lines do you want to display?10
         *
        ***
       *****
      *******
     *********
    ***********
   *************
  ***************
 *****************
*******************
$ sh test.sh
how many lines do you want to display?18
                 *
                ***
               *****
              *******
             *********
            ***********
           *************
          ***************
         *****************
        *******************
       *********************
      ***********************
     *************************
    ***************************
   *****************************
  *******************************
 *********************************
***********************************

回答2:

#!/bin/sh

echo "input row"
read row
i=0

num_star=1
while [ $i -lt $row ]
do
i=$(($i+1))
j=$(($row-$i))
#print space
while [ 0 -lt $j ]
do
j=$(($j-1))
echo -n " "
done

#print star
n=0
while [ $n -lt $num_star ]
do
n=$(($n+1))
echo -n '*'
done
echo ""
num_star=$(($num_star+2))

done