LoginSignup
7
10

More than 5 years have passed since last update.

bashスクリプトで引数とパイプ経由の両方から情報を取得できるようにする。

Last updated at Posted at 2016-01-04

内容

<スクリプト名>.sh abcまたはecho 'abc' | <スクリプト名>.shのどちらでも情報をできるようにする。

テスト用スクリプトファイル作成

▼ test.sh

#!/usr/local/bin/bash
data=''
if [ -t 0 ] ; then
  data="$1"
else
  data="$(cat -)"
fi
echo "$data"

動作確認

$ chmod 755 ./test.sh
$ ./test.sh 'abc'
abc
$ echo 'def' | ./test.sh 
def
7
10
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
7
10