Skip to content

Bash string manipulation API

Bash parameter expansion — built-in string operations performed on shell variables without external tools.

1 class · 8 methods

string manipulation

8 methods

Bash parameter expansion operators for measuring, slicing and replacing text in variables.

${#var}

Returns the length of the variable's value in characters.

Returns

integer

Example

bash
var="Hello, World"
echo ${#var}  # 12

empty=""
echo ${#empty}  # 0
${var:offset:length}

Extracts a substring starting at offset (0-based) with the given length. Omit length for to-end.

Parameters

NameTypeDescription
offsetintegerStart position (negative counts from end).
lengthintegerNumber of characters (optional).

Returns

string

Example

bash
var="Hello, World"
echo ${var:0:5}    # Hello
echo ${var:7}      # World
echo ${var: -5}    # World (note space before -)
${var/old/new}

Replaces the first match of old (glob pattern) with new in var's value.

Parameters

NameTypeDescription
oldpatternGlob pattern to match.
newstringReplacement string.

Returns

string

Example

bash
var="a-b-c"
echo ${var/-/_}  # a_b-c (only first)
${var//old/new}

Replaces all matches of old (glob pattern) with new in var's value.

Parameters

NameTypeDescription
oldpatternGlob pattern to match.
newstringReplacement string.

Returns

string

Example

bash
var="a-b-c"
echo ${var//-/_}  # a_b_c (all matches)

path="/usr/local/bin"
echo ${path//\//_}  # _usr_local_bin (escape / in pattern)
${var#prefix}

Removes the shortest match of prefix from the beginning of var's value.

Parameters

NameTypeDescription
prefixpatternGlob pattern to remove from the front.

Returns

string

Example

bash
path="/usr/local/bin"
echo ${path#/usr}  # /local/bin

file="archive.tar.gz"
echo ${file#*.}  # tar.gz (shortest)
${var%suffix}

Removes the shortest match of suffix from the end of var's value.

Parameters

NameTypeDescription
suffixpatternGlob pattern to remove from the end.

Returns

string

Example

bash
file="archive.tar.gz"
echo ${file%.gz}   # archive.tar
echo ${file%.*}    # archive.tar (shortest from end)
echo ${file%%.*}   # archive (longest from end)
${var^^}

Returns the value of var converted to uppercase. Requires Bash 4.0+.

Returns

string

Example

bash
var="Hello, World"
echo ${var^^}  # HELLO, WORLD
${var,,}

Returns the value of var converted to lowercase. Requires Bash 4.0+.

Returns

string

Example

bash
var="Hello, World"
echo ${var,,}  # hello, world