1 / 12

第3回Bashゼミ

第3回Bashゼミ. for 文処理について 発表者 直江 宗紀. for 文. for 文 do ~ done で囲った部分を繰り返す for 文の記述形式 for 変数 in 値 ( 複数可 ) for 文の構文例. for 変数 in 引数 1 引数 2 … do   処理 done. for 文の記述例. プログラム例. [ 実行結果 ] a b c d e f g. for x in a b c d e f g do echo $x done. パラメータ変数との連携. パラメータ変数とは …

albert
Download Presentation

第3回Bashゼミ

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 第3回Bashゼミ for文処理について 発表者 直江 宗紀

  2. for文 • for文 • do~doneで囲った部分を繰り返す • for文の記述形式for 変数 in 値(複数可) • for文の構文例 for 変数 in 引数1 引数2 … do   処理 done

  3. for文の記述例 • プログラム例 [実行結果] a b c d e f g for x in a b c d e f g do echo $x done

  4. パラメータ変数との連携 • パラメータ変数とは… • スクリプト実行時、スクリプトに渡す引数列 • $@,$*,等、スクリプトに渡す引数を参照できる • パラメータ変数を用いたプログラム例 [test.sh] #!/bin/bash for arg in $@ do echo ${arg} done [実行結果] >test.sh aa bb cc dd >aa >bb >cc >dd

  5. 他のコマンドとの連携 • for構文では・・・ • 他のコマンドや配列を用いて利用可能 • 利用可能コマンドとして→ seqなどが挙げられる • seqとは • 指定した数字の間をカウントし表示する • 例:seq 1 2 10 意味:1から10まで2足しながらカウントする

  6. seqコマンド(1) • seq –数字シークエンス表示コマンド • 記述 • seq [OPTION] LAST • seq [OPTION] FIRST LAST • seq [OPTION] FIRST Increment LAST • オプション • -f:フォーマット指定(%e, %f ,%g のうち1つ) • -s:指定文字列を区切りにする • -w:数字桁を揃えるために上位桁に0を入れる

  7. seqコマンド(2) • オプションについて(続き) • -f • 指定フォーマット[%e,%f,%g](通常は%g) • %e : 浮動小数点表示(記述例:1.0000e+00) • %f : 小数表示 • %g : 整数表示(%e,%f表示の際、指定最終値は表示されない)

  8. seqコマンド(3) • オプションについて(続き) • -s • 指定した文字列を区切り文字とする(通常は“\n”) • 例seq –s ‘,’ 1 2 10[出力結果]1,3,5,7,9

  9. seqコマンド(4) • オプションについて(続き) • -w • 表示桁を揃えるために0を出力 • 例:seq –w 1 10 [出力結果] 01 02 03 04 05 06 07 08 09 10

  10. seqコマンド(5) • オプションについて • 記述位置はseqのすぐ後でのみ有効(数字の後ろではエラーとなる) • 例:seq –f %f 1 2 10 [実行結果] 1.000000 3.000000 5.000000 7.000000 9.000000

  11. 連携プログラム例 • プログラム例 for a in seq 1 2 10 do echo $a done [実行結果] 1 3 5 7 9 1から順に2飛びずつカウントする

  12. 練習問題 • コマンドライン上から任意の数字を渡した時、1からその数字までの総和を求めて表示するスクリプトを作成せよ。 • コマンドライン上から任意の数字を渡した時、その数字までに幾つ素数があるのかをカウントし、その結果を表示するスクリプトを作成せよ。(コマンド”factor”を利用する)

More Related