LoginSignup
2
1

More than 5 years have passed since last update.

シェルのif文で標準入力を条件式の値として使う

Last updated at Posted at 2018-11-02

シェルでif文はif [ 条件式 ]; then ...のような感じで書くことが多いですが、[は実はtestコマンドへのエイリアスでしかなく、"${var}" = 'hoge'のような比較を行っているのは、実はtestコマンドです。
iftestコマンドの終了ステータスが0かそれ以外かしか見ていません。
そのため、ifのあとに置くコマンドは、test以外のなんでもokです。

ためしに、greptestコマンドのかわりに使って、標準入力に渡された文章が質問かそうでないかを判断するスクリプトを書いてみます。

ezoe.sh
#!/bin/sh
# ^ 行頭
# ..* 任意の1文字以上
# [??]* 全角のはてなと半角のはてな0個以上
# $ 行末
if grep '^..*ですか[??]*$' > /dev/null; then
  echo "質問である"
else
  echo "質問ではない"
fi
実行結果(入力文が質問の場合)
$ echo 'ご注文はうさぎですか?' | ./ezoe.sh
質問である
$ echo 'ご注文はうさぎですか?' | ./ezoe.sh 
質問である
$ echo 'ご注文はうさぎですか' | ./ezoe.sh
質問である
実行結果(入力文が質問でない場合)
$ echo 'ご注文はうさぎです' | ./ezoe.sh
質問ではない

bashのPOSIX互換モードとdashで試しました。

2
1
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
2
1