動作環境

$ echo $SHELL
/bin/bash

Hello World

$ vim hello.sh
#!/bin/bash

echo "hello world"
exit 0
# echo "hello world"; exit 0 でも可
$ chmod +x hello.sh
./hello.sh
hello world

変数を使ってみよう

#!/bin/bash

# 変数の代入は"="の前後にスペースを空けてはいけない

s="hello"

# 変数を利用する場合は"$"を使う
# 以下の何れかの書き方でOK

echo $s
echo "$s"
echo "${s}"

# 文字列の連結
echo $s$s
echo "$s $s"

# シングルクォーテーションは変数展開されない
echo '$s'
$ ./hello.sh
hello
hello
hello
hellohello
hello hello
$s

数値演算をしてみよう

#!/bin/bash
x=10
echo $x+2   # "$x+2"という文字列となり計算されない
echo `expr $x + 2`
$ ./hello.sh
10+2
12

四則演算をしてみよう

#!/bin/bash
x=10
echo `expr $x - 2`   # 引き算
echo `expr $x / 2`   # 割り算
echo `expr $x \* 2`   # 掛け算
echo `expor \( $x + 5 \) \* 2`   # 括弧を含む計算
# *や()の前にエスケープシーケンスが必要。エスケープしないとsyntax errorとなる。
$ ./hello.sh 
8
5
20
30
#!/bin/bash
readonly FILE_NAME="hello.sh"
FILE_NAME="hello2.sh"
$ ./hello.sh 
./hello.sh: line 11: FILE_NAME: readonly variable

配列を使ってみよう

#!/bin/bash
a=(2 4 6)
echo $a   # 配列aの先頭の要素
echo ${a[1]}   # 配列aの2番目の要素
echo ${a[@]}   # 配列aの全ての要素
echo ${#a[@]}   # 配列aの要素数
$ ./hello.sh 
2
4
2 4 6
3
#!/bin/bash
a=(2 4 6)

# 配列の要素を変更する
a[2]=10
echo ${a[@]}

# 配列の要素を追加する
a+=(20 30)
echo ${a[@]}

$ ./hello.sh 
2 4 10
2 4 10 20 30
#!/bin/bash
# dateコマンドの結果を表示する
d=(`date`)
echo ${d[3]}
$ date
Wed May  4 06:46:44 CEST 2016
$ ./hello.sh 
06:47:01

条件式を評価してみよう

#!/bin/bash
test 1 -eq 2; echo $?
# "$?"は直前に行った条件式が正常終了したかを返す
$ ./hello.sh 
1
#!/bin/bash
test 1 -eq 1; echo $?
$ ./hello.sh 
0
# 数値
# -eq ... equal (等号)
# -ne ... not equal (不等号)
# -gt ... greater than (より大きい)
# -ge ... greater than or equal (以上)
# -lt ... less than (より小さい)
# -le ... less than or equal (以下)
# 文字列
# = ... equal
# != ... not equal
# ファイル
# -nt ... newer than (より新しい)
# -ot ... older than (より古い)
# -e ... exit (存在するかどうか)
# -d ... directory (ディレクトリかどうか)
test -e hello.sh; echo $?   # 0が返る
# 論理演算子
# -a ... and
# -o ... or
# ! ... not
test 1 -eq 1 -a 2 -eq 2; echo $?   # 0が返る

if文で条件分岐をしてみよう

#!/bin/bash
x=70
if test $x -gt 60   # testは[]で置き換え可
then
   echo "ok!"
elif [ $x -gt 40 ]; then
   echo "soso..."
else
   echo "ng..."
fi
#!/bin/bash
x=70
if [ $x -gt 60 ]; then   # testを[]で置き換えた記法
   echo "ok!"
elif [ $x -gt 40 ]; then
   echo "soso..."
else
   echo "ng..."
fi
$ ./hello.sh 
ok!

case文で条件分岐をしてみよう

signal="red"
case $signal in
   "red")
      echo "stop!"
      ;;
   "yellow")
       echo "caution!"
       ;;
    "green")
       echo "go!"
       ;;
    *)   # 上記の何れにも該当しない場合
       echo "..."
       ;;
esac

while文でループ処理をしてみよう

i=0
while [ $i -lt 10 ]
do
    i=`expr $i + 1`
    echo $i
done
$ ./hello.sh 
1
2
3
4
5
6
7
8
9
10
i=0
while :   # 無限ループ
do
    i=`expr $i + 1`

    if [  $i -eq 3 ]; then
      continue
    fi

    if [  $i -gt 10 ]; then
      break
    fi

    echo $i
done
$ ./hello.sh 
1
2
4
5
6
7
8
9
10

for文でループ処理をしてみよう

for i in 1 2 3 4 5
do
    echo $i
done
a=(1 2 3 4 5)
for i in ${a[@]}
do
    echo $i
done
for i in `seq 1 100`   # 1〜100まで
do
    echo $i
done

トップ   新規 一覧 単語検索 最終更新   ヘルプ   最終更新のRSS