[LINUX] Variable parameter expansion of bash

Introduction

I will forget the variable parameter expansion of bash soon, so I will organize it.

Part of bash parameter expansion

notation meaning
${Variable name#pattern} 最短マッチで、patternに前方一致した部分を取り除く
${Variable name##pattern} 最長マッチで、patternに前方一致した部分を取り除く
${Variable name%pattern} 最短マッチで、patternに後方一致した部分を取り除く
${Variable name%%pattern} 最長マッチで、patternに後方一致した部分を取り除く

There are many notations other than the above, but for the time being, there are four.

Example of use

$ {Variable name #Pattern}

$ {Variable name #Pattern} is a` parameter expansion that removes the part that matches the pattern with the shortest match.

.sh


#!/bin/bash

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

home/name/abc.txt

The shortest match is the ** shortest ** string that matches the specified pattern.

pattern */
String /home/name/abc.txt
Shortest match In front of home/
result home/name/abc.txt

$ {Variable name ## pattern}

$ {Variable name #Pattern} is thelongest match, and is aparameter expansion that removes the prefix matching part of the pattern.

.sh


#!/bin/bash

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

abc.txt

The longest match refers to the ** longest ** string that matches the specified pattern.

pattern */
String /home/name/abc.txt
Longest match /home/name/
result abc.txt

It can be used to get the filename from the file path.

$ {Variable name% pattern}

$ {Variable name% pattern} is a parameter expansion that removes the trailing part of the pattern with the shortest match.

.sh


#!/bin/bash

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

/home/name
pattern /*
String /home/name/abc.txt
Shortest match abc.txt
result /home/name

It can be used to get the directory of the file path without the filename.

$ {Variable name %% pattern}

$ {Variable name %% pattern} is a `parameter expansion that removes the part that is the longest match and the trailing part of the pattern.

.sh


#!/bin/bash

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

(None)
pattern /*
String /home/name/abc.txt
Longest match /home/name/abc.txt
result (None)

reference

New Linux textbook

Recommended Posts

Variable parameter expansion of bash
[Python] Correct usage of map
Variable parameter expansion of bash
python variable expansion, format
About variable of chainer
[Personal memo] Auto-completion of bash
Handling of quotes in [bash]
Expansion by argument of python dictionary
Judgment of holidays including holidays with bash