LoginSignup
0
0

More than 5 years have passed since last update.

bsh-if文

Last updated at Posted at 2019-03-05

Shellのif文について

shell のif文で if test -f test.txtだのif [ -f test.txt ] など書き方があって、
意味を忘れがちになってしまうので、shellのif文について簡単なメモ書きでまとめます。

if文の前にtestコマンドについて

testコマンドとは、条件式の評価をして真偽値を返却してくれるコマンド。
ファイルの有無や文字列比較に用いることが多く、if文を書くときに必ず出てくると言っていいほどのコマンドです。

if文の基本形

#!/bin/sh
if test -f test.txt
then
  echo 'test.txt'
elif test -f text.sh
then
  echo 'test.sh'
else
  echo 'nothing'
fi
  • if文はifで始まりfiで終わります。
  • そして、条件式のあとにthenをつけて、コマンドの実行文を書きます。

条件部を1行で

#!/bin/sh
if test -f test.txt; then
  echo 'test.txt'
elif test -f text.sh; then
  echo 'test.sh'
else
  echo 'nothing'
fi
  • 条件部の最後にセミコロンをつけて、1行で表現

testコマンドの省略

#!/bin/sh
if [ -f test.txt ]; then
  echo 'test.txt'
elif [ -f text.sh ]; then
  echo 'test.sh'
else
  echo 'nothing'
fi
  • testコマンドを省略した場合、[]で条件をくくる。
  • []内部の空白は文法上必須だから注意
0
0
1

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
0
0