3
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

bashの変数パラメータ展開

Posted at

はじめに

bashの変数パラメータ展開をすぐ忘れてしまうので整理する。

bashのパラメータ展開の一部

記法 意味
${変数名#パターン} 最短マッチで、パターンに前方一致した部分を取り除く
${変数名##パターン} 最長マッチで、パターンに前方一致した部分を取り除く
${変数名%パターン} 最短マッチで、パターンに後方一致した部分を取り除く
${変数名%%パターン} 最長マッチで、パターンに後方一致した部分を取り除く

上記以外にも沢山の記法があるがとりあえず4つ。

使用例

${変数名#パターン}

${変数名#パターン}は、最短マッチで、パターンに前方一致した部分を取り除くパラメータ展開である。

.sh
# !/bin/bash

filepath=/home/name/abc.txt
echo "${filepath#*/}"

home/name/abc.txt

最短マッチとは、指定するパターンにマッチする文字列のうち最も短いものを指す。

パターン */
文字列 /home/name/abc.txt
最短マッチ homeの手前の/
結果 home/name/abc.txt

${変数名##パターン}

${変数名#パターン}は、最長マッチで、パターンに前方一致した部分を取り除くパラメータ展開である。

.sh
# !/bin/bash

filepath=/home/name/abc.txt
echo "${filepath##*/}"

abc.txt

最長マッチは指定するパターンにマッチする文字列のうち最も長いものを指す。

パターン */
文字列 /home/name/abc.txt
最長マッチ /home/name/
結果 abc.txt

ファイルパスからファイル名を取得するのに利用できる。

${変数名%パターン}

${変数名%パターン} は、最短マッチで、パターンに後方一致した部分を取り除くパラメータ展開である。

.sh
# !/bin/bash

filepath=/home/name/abc.txt
echo "${filepath%/*}"

/home/name
パターン /*
文字列 /home/name/abc.txt
最短マッチ abc.txt
結果 /home/name

ファイルパスからファイル名を除いたディレクトリを取得するのに利用できる。

${変数名%%パターン}

${変数名%%パターン} は、最長マッチで、パターンに後方一致した部分を取り除くパラメータ展開である。

.sh
# !/bin/bash

filepath=/home/name/abc.txt
echo "${filepath%%/*}"

(なし)
パターン /*
文字列 /home/name/abc.txt
最長マッチ /home/name/abc.txt
結果 (なし)

参考

新しいLinuxの教科書

3
5
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
3
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?