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: "$@" passes every argument on to the next command, spaces and all

Shell
~/tips/tip-shell-quoted-dollar-at

f() {

Forward the arguments of a script or function without breaking names with spaces.

A wrapper script or function that hands its arguments to another command has three ways to write it, and only one of them is right almost every time.

Try it with an argument that contains a space:

f() {
  printf '[%s]' "$@"; echo
  printf '[%s]' $*;   echo
  printf '[%s]' "$*"; echo
}
f "my file.txt" two

The output:

[my file.txt][two]
[my][file.txt][two]
[my file.txt two]

"$@" keeps each argument as it was. Unquoted $* (or $@) splits on spaces, so my file.txt becomes two files that do not exist. "$*" glues everything into one string.

So a wrapper looks like this:

#!/bin/sh
exec rsync -a --info=progress2 "$@"

"$*" has its place: when you want one string, like in a log message echo "called with: $*". It joins with the first character of IFS, a space by default. For passing arguments on, I’d always use "$@", with the quotes.

Further reading: Bash manual: Special Parameters

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