Skip to content

Instantly share code, notes, and snippets.

@eggplants
Last active February 9, 2022 03:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eggplants/9af05967cc21ec0a0d398f9fbecf03d6 to your computer and use it in GitHub Desktop.
Save eggplants/9af05967cc21ec0a0d398f9fbecf03d6 to your computer and use it in GitHub Desktop.
Bash >= 4

bashの変数展開記法まとめ

${v}:参照
${v:-word}:vが空/未定義->wordを返す
${v:=word}:vが空/未定義->wordを代入し返す
${v-word}:vが未定義->wordを返す
${v=word}:vが未定義->wordを代入し返す
#############################################################################################
${v:?word}:vが空/未定義->wordをエラーメッセージとしてエラー発生
${v:+word}:vが空でない/定義済->wordを返す
${v:offset}:vの値のoffsetのインデックスから末尾までを返す(v[offset:])
${v:offset:length}:vの値のoffsetのインデックスからlength文字分出力(v[offset:length])
#############################################################################################
${!prefix*}:prefixを先頭に持つ定義済み変数を検索し返す
${!prefix@}:同上
${!v[@]}:連想配列vのキー名を列挙
${!v[*]}:同上
${v[@]}:連想配列vの値を列挙
${v[*]}:同上
#############################################################################################
${#v}:vの値の文字列長を返す
${#v[*]}:配列vの要素数を返す
${v#exp}:vの値のexpにマッチした部分以降を返す(最短一致)
${v##exp}:vの値のexpにマッチした部分以降を返す(最長一致)
${v%exp}:vの値のexpにマッチした部分以前を返す(最短一致)
${v%%exp}:vの値のexpにマッチした部分以前を返す(最長一致)
*上記4つは配列の値には一括で適用
#############################################################################################
${v/exp/string}:vの値を置換し返す(sub)
${v//exp/string}:vの値を置換し返す(gsub)
*上記2つは#expで先頭から、%expで末尾から置換し返す
#############################################################################################
${v^}:vの値の小文字を大文字に変換し返す(capitalize)
${v^^}:vの値の小文字を全て大文字に変換し返す(upcase)
${v,}:vの値の大文字を小文字に変換し返す(lowercase)
${v,,}:vの値の小文字を全て大文字に変換し返す(downcase)
${v~}:vの値の大文字/小文字を全て反転し返す(swapcase)
*上記5つは、${v^exp}のようにするとexpにマッチした部分から大文字小文字変換を行う
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment