Tutorial by Examples

var='0123456789abcdef' # Define a zero-based offset $ printf '%s\n' "${var:3}" 3456789abcdef # Offset and length of substring $ printf '%s\n' "${var:3:4}" 3456 4.2 # Negative length counts from the end of the string $ printf '%s\n' "${var:3:-5}" 3456789a...
# Length of a string $ var='12345' $ echo "${#var}" 5 Note that it's the length in number of characters which is not necessarily the same as the number of bytes (like in UTF-8 where most characters are encoded in more than one byte), nor the number of glyphs/graphemes (some of which ...
4.0 To uppercase $ v="hello" # Just the first character $ printf '%s\n' "${v^}" Hello # All characters $ printf '%s\n' "${v^^}" HELLO # Alternative $ v="hello world" $ declare -u string="$v" $ echo "$string" HELLO WORLD To l...
Bash indirection permits to get the value of a variable whose name is contained in another variable. Variables example: $ red="the color red" $ green="the color green" $ color=red $ echo "${!color}" the color red $ color=green $ echo "${!color}" the ...
${parameter:-word} If parameter is unset or null, the expansion of word is substituted. Otherwise, the value of parameter is substituted. $ unset var $ echo "${var:-XX}" # Parameter is unset -> expansion XX occurs XX $ var="" # Parameter is null ...
The semantics for this are similar to that of default value substitution, but instead of substituting a default value, it errors out with the provided error message. The forms are ${VARNAME?ERRMSG} and ${VARNAME:?ERRMSG}. The form with : will error our if the variable is unset or empty, whereas the ...
Shortest match: $ a='I am a string' $ echo "${a#*a}" m a string Longest match: $ echo "${a##*a}" string
Shortest match: $ a='I am a string' $ echo "${a%a*}" I am Longest match: $ echo "${a%%a*}" I
First match: $ a='I am a string' $ echo "${a/a/A}" I Am a string All matches: $ echo "${a//a/A}" I Am A string Match at the beginning: $ echo "${a/#I/y}" y am a string Match at the end: $ echo "${a/%g/N}" I am a strinN Replace a pattern wi...
Variables don't necessarily have to expand to their values - substrings can be extracted during expansion, which can be useful for extracting file extensions or parts of paths. Globbing characters keep their usual meanings, so .* refers to a literal dot, followed by any sequence of characters; it's ...
You can use Bash Parameter Expansion to emulate common filename-processing operations like basename and dirname. We will use this as our example path: FILENAME="/tmp/example/myfile.txt" To emulate dirname and return the directory name of a file path: echo "${FILENAME%/*}" ...

Page 1 of 1