GNU/Linux >> Linux の 問題 >  >> Linux

星のピラミッドを出力するシェルスクリプト

基本

ここでは、以下に示すように、星のピラミッドを 2 つの部分に分けて印刷します。ユーザーから提供された数値をループし、for ループを使用して星の前半を出力し、別の for ループを使用して残りの半分を出力します。スペースと改行文字は別のセクションに追加されます。

スクリプト

1. ファイル /tmp/star_pyramid.sh を編集し、以下のスクリプトを追加します:

#!/bin/bash
makePyramid()
{
  # Here $1 is the parameter you passed with the function i,e 5
  n=$1;

  # outer loop is for printing number of rows in the pyramid
  for((i=1;i<=n;i++))
  do

      # This loop print spaces required
      for((k=i;k<=n;k++))
      do
        echo -ne " ";
      done

      # This loop print part 1 of the the pyramid
      for((j=1;j<=i;j++))
      do
      echo -ne "*";
      done

      # This loop print part 2 of the pryamid.
      for((z=1;z<i;z++))
      do
      echo -ne "*";
      done
      
      # This echo is used for printing a new line
      echo;
  done
}

# calling function
# Pass the number of levels you need in the parameter while running the script.
makePyramid $1

2. スクリプトに実行権限を付与します。

# chmod +x /tmp/star_pyramid.sh

3. スクリプトの実行中に、出力に必要なレベル数を指定します。例:

$ /tmp/star_pyramid.sh 10
          *
         ***
        *****
       *******
      *********
     ***********
    *************
   ***************
  *****************
 *******************

別の方法

シェル スクリプトを使用して星のピラミッドを出力する別の方法を次に示します。

#!/bin/bash

clear
echo -n "Enter the level of pyramid: "; read n

star=''
space=''

for ((i=0; i<n; i++ ))
do
space="$space "
done

echo "$space|"

for (( i=1; i<n; i++ ))
do

star="$star*"
space="${space%?}"
echo "$space$star|$star";

done

スクリプトを実行可能にして実行します。

$ /tmp/star_pyramid.sh
Enter the level of pyramid: 10
          |
         *|*
        **|**
       ***|***
      ****|****
     *****|*****
    ******|******
   *******|*******
  ********|********
 *********|*********

シェル スクリプトを使用した数字のピラミッド

上記の 2 つの例と同様に、以下のスクリプトを使用して数字のピラミッドを出力することもできます。

#!/bin/bash

read -p "How many levels? : " n

for((i = 0; i < n; i++))
do
k=0
while((k < $((i+1))))
do
echo -e "$((i+1))\c"
k=$((k+1))
done

echo " "
done

スクリプトを実行可能にして実行します。

$ /tmp/star_pyramid.sh
How many levels? : 5
1
22
333
4444
55555


Linux
  1. シェルスクリプトでタイムアウトしますか?

  2. ソースシェルスクリプトへのパスを決定しますか?

  3. シェルスクリプトの予期しない動作?

  1. シェルスクリプトで一時ファイルを作成するにはどうすればよいですか?

  2. インタラクティブシェルのセッションのプロセスとスクリプトのプロセス?

  3. $の意味は?シェルスクリプトでは?

  1. 実行時にスクリプトでシェルを決定しますか?

  2. シェルスクリプトでスイッチを処理する方法は?

  3. Linux シェルの音訳スクリプト