An Amusing Shell Trick
Sometimes a function takes arguments passed down from a caller like this:
my_fun() {
do_something_fun "$@"
}
On occasion you need to call something that takes arguments in an awkward order. Today’s example is the pattern argument to fd:
do_find() {
local d="$1"
shift
fd -t f "$@" "$d"
}
The pattern argument is $1 within $@ here. But what if there is only one argument to the do_find call? We should supply an empty argument as the pattern.
I know of two ways to do this. The first is to expand to $@ if $1 is defined:
"${1:+$@}"
The second is to prepend an empty string to the "$@" expansion:
"""$@"
I find this last one both highly amusing and more visually striking than the first. And it’s so simple it took years to see!