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: cp file{,.bak} makes a backup copy without typing the name twice

Shell
~/tips/tip-shell-brace-backup-copy

cp /etc/ssh/sshd_config{,.bak}

Expands to a command with the file name and a .bak copy, saving you from typing the path twice.

Before I edit a config file I want a backup, and I do not want to type a long path twice. Brace expansion does it.

Bash expands {a,b} into separate words before running the command. With nothing before the comma you get the bare name once and the name plus a suffix once.

$ cp /etc/ssh/sshd_config{,.bak}
# runs: cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak

It also does ranges and sequences, which makes it a quick way to build several names: mkdir project/{src,docs,tests} or touch log-{01..12}.txt. Check what an expansion produces with echo first. It costs nothing.

The caveat: brace expansion is a text trick and has no idea whether files exist. It also happens before variable expansion, so {1..$n} does not work in Bash; it stays a literal string. Use seq or a C-style loop for that. And it is not in plain POSIX sh, so a script run with sh on Debian or Ubuntu (which is dash) will not expand it.

That makes it a good habit before any edit to a config you cannot easily get back. A backup next to the original also makes diff file file.bak a one-second check afterwards.

Further reading: Bash manual: Brace Expansion, On this site: Alt+. pastes the last argument of your previous command, On this site: sudo !! reruns your last command with sudo

More Shell tips zmv -n '(*).log' '$1.txt' zoxide query -ls project f=$(mktemp --suffix=.json) shopt globskipdots echo $EPOCHSECONDS All Shell tips (78) All topics

Link