brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: ${var:offset:length} cuts a piece out of a bash string

Bash
~/tips/tip-bash-substring-expansion-offset-length

f="backup-2026-11-27.tar.gz"

Takes a fixed part of a string in bash, counting from the start or the end.

Grabbing a few characters out of a string doesn’t need cut -c. Bash has substring expansion built in, and I like that it can count from the end too.

The first number is where to start (counting from 0), the second is how many characters you want. Leave the length out and you get everything to the end:

f="backup-2026-11-27.tar.gz"
echo "${f:7:10}"     # 2026-11-27
echo "${f:7:4}"      # 2026
echo "${f:7}"        # 2026-11-27.tar.gz

A negative offset counts back from the end, so ${f: -6} gives tar.gz. A negative length is read as an offset from the end as well, which means ${f:7:-7} drops the last seven characters and leaves the date. That’s handy for fixed-format names, like the date stamp in backup files or the first eight characters of a long container ID: ${id:0:8}.

The caveat is that space before the minus. Write ${f:-6} without it and bash reads it as the default-value expansion :-, so you get the whole string back (or 6 if the variable is empty), with no error. Either put a space after the colon or wrap the number in parentheses: ${f:(-6)}. Also keep in mind it counts characters, not fields, so it only works well when the position of what you want is fixed. For anything that depends on a separator, I’d use ${f%.*}-style trimming instead.

Further reading: bash(1) manual page

More Bash tips echo {01..10} cmd > file 2>&1 export HISTIGNORE='ls*:pwd:cd*' #rsync -av --delete /srv/media/ /mnt/backup/media/ APP_HOST=example.com All Bash tips (52) All topics

Link