0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Bash の基本文法を、実務でよく使う順に整理しました

0
Posted at

1. コマンドの基本形

command option argument

例:

ls -la /tmp

意味は、

  • ls = コマンド
  • -la = オプション
  • /tmp = 対象

です。

複数コマンドを1行に書く場合は ; で区切れます。

pwd; ls; date

2. 変数

代入するときは = の前後にスペースを入れません。

name="Taro"
age=30

参照するときは $ を付けます。

echo $name
echo $age

より安全なのは ${} です。

echo "${name}"

文字列とつなげるときに特に便利です。

file="${name}_backup.txt"

これは:

Taro_backup.txt

になります。

3. クォート

Bashでは " " と ' ' の違いが重要です。

ダブルクォートは変数展開されます。

name="Taro"
echo "Hello $name"

結果:

Hello Taro

シングルクォートはそのまま文字列として扱います。

echo 'Hello $name'

結果:

Hello $name

基本的には、変数を使うなら:

echo "$name"

のようにダブルクォートで囲むのがおすすめです。

4. コマンド置換

コマンドの実行結果を変数に入れられます。

now=$(date)
echo "$now"

昔の書き方として、

now=`date`

もありますが、現在は $() が推奨です。

5. 標準出力とリダイレクト

通常の出力をファイルに保存できます。

上書き:

echo "hello" > test.txt

追記:

echo "world" >> test.txt

エラー出力だけ保存:

command 2> error.log

通常出力とエラー出力の両方:

command > output.log 2>&1

Bashでは簡略形もあります。

command &> output.log

6. パイプ |

前のコマンドの結果を次のコマンドに渡します。

ps aux | grep nginx

流れは:

ps aux
  ↓
grep nginx

です。

よく使う例:

cat access.log | grep "404"

ただし grep は直接ファイルを指定できるので、

grep "404" access.log

のほうがシンプルです。

7. 条件実行 && と ||

&& は「前が成功したら次を実行」です。

mkdir backup && cp file.txt backup/

mkdir が成功したときだけ cp が実行されます。

|| は「前が失敗したら次を実行」です。

mkdir backup || echo "mkdir failed"

組み合わせることもできます。

command && echo "success" || echo "failed"

8. 終了ステータス

Linux/Bash のコマンドは終了時に数値を返します。

基本は:

0 = 成功
0以外 = 失敗

直前の結果は $? で確認できます。

ls /tmp
echo $?

成功なら:

0

になります。

この仕組みが if や && に使われています。

9. if文

基本形:

if 条件; then
  処理
fi

例:

if [ -f "/tmp/test.txt" ]; then
  echo "ファイルがあります"
fi

else:

if [ -f "/tmp/test.txt" ]; then
  echo "exists"
else
  echo "not found"
fi

複数条件:

if 条件1; then
  ...
elif 条件2; then
  ...
else
  ...
fi

10. [ ] による条件判定

文字列比較:

if [ "$name" = "Taro" ]; then
  echo "match"
fi

空文字:

[ -z "$name" ]

空でない:

[ -n "$name" ]

ファイルが存在:

[ -f "$file" ]

ディレクトリが存在:

[ -d "$dir" ]

11. 数値比較

Bashでは数値比較に専用演算子があります。

if [ "$age" -gt 20 ]; then
  echo "over 20"
fi

代表的なもの:

-eq  等しい
-ne  等しくない
-gt  >
-ge  >=
-lt  <
-le  <=

例えば:

[ "$a" -eq "$b" ]
[ "$a" -gt "$b" ]

12. [[ ]]

Bashでは [ ] より [[ ]] のほうが便利な場合があります。

if [[ "$name" == "Taro" ]]; then
  echo "match"
fi

ワイルドカードも使えます。

if [[ "$file" == *.log ]]; then
  echo "log file"
fi

Bashスクリプトなら [[ ]] を使うことが多いです。

13. while文

基本:

while 条件; do
  処理
done

例:

count=1

while [ "$count" -le 5 ]; do
  echo "$count"
  count=$((count + 1))
done

結果:

1
2
3
4
5

無限ループ:

while true; do
  date
  sleep 5
done

14. for文

よく使う形:

for item in a b c; do
  echo "$item"
done

結果:

a
b
c

ファイルを処理:

for file in *.log; do
  echo "$file"
done

数値:

for i in {1..5}; do
  echo "$i"
done

15. C言語風 for

Bashではこういう書き方もできます。

for ((i=0; i<5; i++)); do
  echo "$i"
done

結果:

0
1
2
3
4

16. 算術演算

整数計算は $(( )) を使います。

a=10
b=20

c=$((a + b))

echo "$c"

結果:

30

代表例:

$((a + b))
$((a - b))
$((a * b))
$((a / b))
$((a % b))

インクリメント:

((count++))

も使えます。

17. 関数

基本:

hello() {
  echo "Hello"
}

呼び出し:

hello

引数も渡せます。

hello() {
  echo "Hello $1"
}

hello Taro

結果:

Hello Taro

18. スクリプトの引数

例えば:

./test.sh aaa bbb

と実行した場合、

$0

はスクリプト名、

$1

は aaa、

$2

は bbb です。

引数の個数:

$#

全引数:

"$@"

非常によく使います。

例えば:

for arg in "$@"; do
  echo "$arg"
done

19. case文

複数条件を分岐するときに便利です。

case "$1" in
  start)
    echo "start"
    ;;
  stop)
    echo "stop"
    ;;
  restart)
    echo "restart"
    ;;
  *)
    echo "unknown"
    ;;
esac

サーバー管理スクリプトなどでよく見ます。

20. 配列

Bashでは配列も使えます。

servers=("web01" "web02" "db01")

参照:

echo "${servers[0]}"

全部:

echo "${servers[@]}"

ループ:

for server in "${servers[@]}"; do
  echo "$server"
done

21. コメント

# から後ろはコメントです。

# バックアップ処理
cp data.sql backup.sql

ただし1行目の、

#!/bin/bash

は特別で、shebang と呼ばれます。

このスクリプトを何で実行するか指定します。

現在なら、

#!/usr/bin/env bash

もよく使われます。

22. 実行権限

スクリプトを作っただけでは、

./script.sh

で実行できない場合があります。

実行権限を付けます。

chmod +x script.sh

その後:

./script.sh

で実行できます。

23. break と continue

ループを途中で終了:

for i in {1..10}; do
  if [ "$i" -eq 5 ]; then
    break
  fi
  echo "$i"
done

結果:

1
2
3
4

continue は次のループへ進みます。

for i in {1..5}; do
  if [ "$i" -eq 3 ]; then
    continue
  fi

  echo "$i"
done

結果:

1
2
4
5

24. バックグラウンド実行 &

末尾に & を付けるとバックグラウンドで実行します。

sleep 100 &

ジョブ確認:

jobs

フォアグラウンドへ戻す:

fg

25. $(...) と $((...)) の違い

ここは混乱しやすいです。

コマンドを実行:

$(date)

計算:

$((1 + 2))

つまり、

$( )   コマンド実行
$(( )) 数値計算
${ }   変数展開

と覚えると分かりやすいです。

26. 実務でよく見る Bash スクリプト

例えばサーバーのディスク使用率をチェックするとします。

#!/usr/bin/env bash

usage=$(df / | awk 'NR==2 {print $5}' | tr -d '%')

if [ "$usage" -gt 80 ]; then
  echo "WARNING: disk usage is ${usage}%"
else
  echo "OK: disk usage is ${usage}%"
fi

この短いスクリプトだけでも、

変数
コマンド置換
パイプ
if
数値比較
文字列展開

という Bash の基本要素が全部入っています。

最初に覚えるべきもの

Bashを使うなら、まずこのあたりを覚えればかなり実用的です。

# 変数
name="test"
echo "$name"

# コマンド結果
now=$(date)

# 条件
if [ -f "$file" ]; then
  echo "exists"
fi

# ループ
for file in *.log; do
  echo "$file"
done

# while
while true; do
  date
  sleep 5
done

# パイプ
ps aux | grep nginx

# リダイレクト
command > output.log
command >> output.log
command 2> error.log

# 成功時だけ実行
mkdir test && cd test

特にインフラやサーバー運用では、**「コマンド → パイプ → grep/awk/sed → if → for/while → リダイレクト」**の組み合わせを理解すると、ログ解析・監視・バックアップ・デプロイ処理などをかなり自動化できるようになります。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?