Bashとは
Linux/Unixのシェルで、コマンド実行や運用自動化に使われる。
Bashは、Linux運用や自動化で候補になります。初学者から運用者までで、シェルスクリプト・インタプリタという特徴があります。
| 項目 | 内容 |
|---|---|
| 主な用途 | Linux運用、自動化、CI、ログ処理 |
| 型 | シェルスクリプト |
| 実行方式 | インタプリタ |
| 学習難易度 | 初学者から運用者まで |
| パッケージ管理 | OSパッケージ |
| 公式サイト | https://www.gnu.org/software/bash/ |
| 公式ドキュメント | https://www.gnu.org/software/bash/manual/ |
| 公式更新源 | https://savannah.gnu.org/news/?group=bash |
最小コード例
Section titled “最小コード例”find /var/log -name "*.log" -mtime -7 -print向いていること
Section titled “向いていること”- Linux運用
- 自動化
- CI
- ログ処理
検索意図から見る要点
Section titled “検索意図から見る要点”このページへ検索から来た人は、まず「これは何の記法なのか」「今も実用されるのか」「どの資料を確認すればよいのか」を知りたいはずです。理解の入口になる情報を次のように整理します。
| 観点 | 内容 |
|---|---|
| 種別 | シェル / スクリプト言語 |
| 概要 | GNU Bourne Again Shell。Unix/Linux運用、自動化、シェルスクリプトに使われる。 |
| 読み始める順番 | 公式サイト、仕様、実装例、既存資産の順に見ると判断しやすい |
読むときは、現在の実用言語なのか、過去の資産を読むための言語なのか、特定製品のためのDSLなのかを分けると判断しやすくなります。
追加調査で押さえる実務ポイント
Bashは、GNU Projectが開発するUnix shell兼command languageです。interactive terminalでcommandを実行する用途と、text fileを非対話shellで順番に実行するscript用途を持ちます。一般的なapplication languageとは異なり、process、file descriptor、pipeline、environment variable、exit statusを操作することが中心です。短い運用automationに向きますが、複雑なdata構造や大規模applicationには別言語を検討します。
基本情報
| 項目 | 内容 |
|---|---|
| 正式名 | GNU Bash |
| 種別 | shell / command language |
| source | .shが一般的 |
| runtime | bash process |
| typing | string中心、integer属性あり |
| package | OS package |
| 用途 | CLI、automation |
| license | GPL |
Shellの処理
- inputを読む。
- tokenとoperatorをparseする。
- alias・parameter・command substitutionを展開する。
- redirectionを設定する。
- commandを探す。
- builtinまたはexternal processを実行する。
- exit statusを返す。
最小例
#!/usr/bin/env bash
set -euo pipefail
for file in "$@"; do
printf '%s
' "$file"
done
入力はcommand line argument、出力は各argumentです。
Quote
| 書き方 | 意味 |
|---|---|
"$var" | word splittingとglobを抑制 |
'$var' | literal |
$var | 通常は避ける |
"$(cmd)" | command substitution |
${var:-default} | default value |
Pipeline
producer | filter | consumer
各commandは別processになり得ます。pipefailを使わない場合、pipeline全体のstatusは通常最後のcommandで決まります。
向く用途
- system administration
- CI glue
- file operation
- process起動
- package installation
- log filter
- deployment entrypoint
向かない用途
- large business logic
- complex JSON transformation
- cross-platform GUI
- high-performance computation
- long-lived service
- rich type safety
POSIX shとの違い
Bash array、[[ ... ]]、process substitution、source等はPOSIX shで動かない場合があります。portable scriptなら#!/bin/shとPOSIX syntaxを使います。
Security
- variableをquoteする
evalを避ける- untrusted filenameをoption扱いさせない
- temporary fileに
mktemp - secretをcommand lineへ出さない
curl | bashを避ける- shellcheckを使う
- executable pathを固定する
Error handling
set -eは万能ではありません。conditional、subshell、pipelineで挙動が変わるため、重要commandは明示的にstatusを確認します。
次に読む
参考リンク
- www.gnu.org - Bash公式
- www.gnu.org - Reference Manual
- savannah.gnu.org - project news