5
7

More than 1 year has passed since last update.

標準入力も受け取れるシェルスクリプト(catコマンド使用)

Last updated at Posted at 2016-02-06

こんにちは。
cat コマンドを使えば、パイプラインからの標準入力でも、引数による指定ファイルの内容も受け取って処理できるシェルスクリプト作りが容易です(下記例)。

総行数を求める例

#!/bin/sh
# If no file arguments are specified, the standard input is used.

# error handling: 入力が何もない場合にはエラー処理しています。
[ $# == 0 ] && [ ! -p /dev/stdin ] && exit 1

# execution: 総行数を求める例です
cat "$@" | wc -l
exit 0

行毎にループを回す例

ただし最終行まで一度に受け取るので大きいサイズの場合は要注意です。

#!/bin/sh
for line in `cat "$@"`
do
  echo $line
done
exit 0
5
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
7