Section Next | Prev


3.4.3 条件判断(if)

if 文は表現式を評価し、真のとき続くコマンドを実行し、偽のとき else 以下 を実行します。
【文法】
if 文には、次の2つの形があります。
単純 if 文
	[ 表現式 ] &&  コマンド	式が真ならコマンド実行
	[ 表現式 ] ||  コマンド	式が偽ならコマンド実行
ブロック if 文
	if  [ 表現式 ]
	then
		コマンド群
	else
		コマンド群
	fi
また、 elif を使用してネストする事もできます。ただし、 elif には fi はつけません。

【例】コマンドの処理結果をもとに続くコマンドのを制御
$ d=/tmp
$ ls -ld $d && echo "$d found"
drwxrwxrwt  4 root root 4096 Oct  6 17:31 /tmp
/tmp found	# 直前の ls コマンドが正常(真)終了し、後続の echo が実行されている
$ ls -ld $d || echo "$d not found"
drwxrwxrwt  4 root root 4096 Oct  6 17:31 /tmp

$ d=/detarame
$ ls -ld $d && echo "$d found"
ls: /detarame: No such file or directory
$ ls -ld $d || echo "$d not found"
ls: /detarame: No such file or directory
/detarame not found # 直前の ls コマンドが異常(偽)終了し、後続の echo が実行されている
【例】簡単なスクリプト[GetSample]
$ cat -n check
     1  #! /bin/bash
     2  # @(#) file type check
     3  #
     4  if [ $# -ne 1 ]; then
     5          echo "usage: $0 file"
     6          exit 1
     7  fi
     8
     9  if [ -f $1 ]; then
    10          echo -e "File $1 is"
    11  elif [ -d $1 ]; then
    12          echo -e "Directory $1 is"
    13  else
    14          echo -e "????????? $1 is"
    15  fi
    16
    17  [ -r $1 ] && echo -e "Readable \c"
    18  [ -w $1 ] && echo -e "Writable \c"
    19  [ -x $1 ] && echo -e "Executable \c"
    20
    21  echo "."

$ check /tmp
Directory /tmp is
Readable Writable Executable .

$ check /bin/bash
File /bin/bash is
Readable Executable .

$ check `tty`
????????? /dev/pts/0 is
Readable Writable .
このシェル・スクリプトは実行時に引き数としてファイル名を1つ渡し、その属性を 表示します。

Section Next | Prev

Copyright 2007 ycosSystems Shell/Body343.html