基礎
そこで、ここでは、以下に示すように、星のピラミッドを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
The post 星のピラミッドを印刷するシェルスクリプト–オタク日記 appeared first on Gamingsym Japan.