if-elif-else
C言語など、一般の言語と同様にif文による条件分岐が記述できます。
elif ('else if'でも'elsif'でもない) であったり、then, fiと記述されるあたりなどが、Rubyとよく似ています。
以下のサンプルでは、testというファイルのステータスを確認するコマンドを用いています。
sample.sh
#!/bin/sh
if test -r sample.sh
then
echo 'sample.sh exists and can be read.'
elif test -f sample.sh; then # 一行で記述するときはセミコロンが必須
echo 'sample.sh exists'
else
echo 'sample.sh does not exist'
fi
if [ -f sample.sh ]; then # []はtestの略記法
echo 1024
fi
実行例 (chmod +x sample.sh を忘れずに)
$ ./sample.sh
sample.sh exists and can be read.
1024
正規表現等を使う (bash 記法)
[[]] で囲むと正規表現等を使えます。
sample.bash
#!/bin/bash
if [[ "aaa" == *aa ]]; then
echo "true"
else
echo "false"
fi
if [[ "aaa" =~ [a-z]{3} ]]; then
echo "true"
else
echo "false"
fi
実行例
$ bash sample.bash
true
true
case
) の左の合致文字列では、ワイルドカードが使用できます。*) とすることで、C言語などのdefault相当の分岐ができます。
sample.sh
#!/bin/sh
VAR=xyz
case $VAR in
XYZ) echo "VAR is XYZ" ;;
xyz) echo "VAR is xyz" ;;
*) echo "ELSE" ;;
esac
実行例
$ ./sample.sh
VAR is xyz
0
Pythonを使ったFlaskアプリ開発が得意
記事の執筆者にステッカーを贈る
有益な情報に対するお礼として、またはコメント欄における質問への返答に対するお礼として、 記事の読者は、執筆者に有料のステッカーを贈ることができます。
さらに詳しく →Feedbacks
ログインするとコメントを投稿できます。





