Suppose I want to generate a filename based on some given variables.
track=01
title="Some title"
album="Some album"
echo ${track}. ${title} (${album})-> 01. Some title (Some album)
Now in the case $album is empty I would get
->01. Some title ()
I would rather want in that case the parenthesis to be removed:
->01. Some title
What I want is something similar to the templates used in foobar like this:
%track%. %title% [(%album%)]
Is it possible to do it in bash (or zsh) but in a single expression like the above and not using if...fi nor nothing like that.
1 Answer
bash: yes, but it's not very pretty:
filename="${track}. ${title}${album:+ ($album)}"The ${var:+value} expands to "value" if $var is both set and non-empty.
Demonstrating:
$ album="Some album"
$ filename="${track}. ${title}${album:+ ($album)}"
$ declare -p filename
declare -- filename="01. Some title (Some album)"
$ album=""
$ filename="${track}. ${title}${album:+ ($album)}"
$ declare -p filename
declare -- filename="01. Some title"
$ unset album
$ filename="${track}. ${title}${album:+ ($album)}"
$ declare -p filename
declare -- filename="01. Some title"ref: 3.5.3 Shell Parameter Expansion
2