Paizaや競技プログラミングでBashを使うために環境構築を行う(シェルスクリプト入門)




txtファイルを3つ作ります。

  • i1.txt
  • i2.txt
  • i3.txt

それぞれのファイルに標準入力する値を入れておきます。


i1.txt

3
a
b
c


i2.txt

5
a
i
u
e
o


i3.txt

2
hoge
hogehoge




メインのコードを書くshファイルを用意します。
改行区切りで値が与えられる場合を想定しました。
nは要素数を表しています。

main.sh

read n
for ((i = 0; i < $n; i++)); do
    read value
    echo $value
done




txtファイルの値をmain.shの標準入力に与えます。
ターミナルで以下のコマンドを実行します。

bash main.sh < i1.txt


実行結果

a
b
c

i1.txtの値が標準入力として反映されています。




ファイルの番号を変えて実行すれば、それに応じた値が標準入力として渡されます。

bash main.sh < i2.txt
bash main.sh < i3.txt