问题
I have a little banner that I display at login
fignow() { figlet -w $(tput cols) $(date +"%b %d, Week %V"); figlet -w $(tput cols) -f univers $(date +"%H:%M"); }
This works fine if the additional fonts are installed to get univers
, but that's not part of the default installation, so I can do the following:
fignow() { figlet -w $(tput cols) $(date +"%b %d, Week %V"); if [ -f /usr/share/figlet/univers.flf ]; then figlet -w $(tput cols) -f univers $(date +"%H:%M"); else figlet -w $(tput cols) $(date +"%H:%M"); fi; }
This also works fine, but I was curious if the if/else/fi
could be removed and the logic could be done inside the command itself, i.e. something like:
fignow() { figlet -w $(tput cols) $(date +"%b %d, Week %V"); figlet -w $(tput cols) -f $(use-univers-or-failback-to-standard.flf-if-univers.flf-is-not-available) $(date +"%H:%M"); }
Is something like that possible?
回答1:
I suggest to use figlist
to avoid hardcoding the themes path:
figlet -w "$(tput cols)" -f "$((figlist | /bin/grep -hw universe) || echo "standard")" "foo"
回答2:
I suggest:
fignow() {
local opts
figlet -w $(tput cols) $(date +"%b %d, Week %V")
[ -f /usr/share/figlet/univers.flf ] && opts="-f univers"
figlet -w $(tput cols) $opts $(date +"%H:%M")
}
Only if the file exists the variable $opts contains the necessary options.
回答3:
Checking for the file or parsing the output of figlist or showfigfonts is inherently fragile. Just call figlet to see if the option is available. Something like:
fignow() {
local font=${1-universe}
figlet -f "$font" a > /dev/null 2>&1 || font=
figlet -w $(tput cols) $(date +"%b %d, Week %V")
figlet -w $(tput cols) ${font:+-f "$font"} $(date +"%H:%M")
}
Note that this is one of those cases where you must not use double quotes around the variable, since you want ${font:+-f "$font"}
to expand to the empty string when $font
is empty. If you use "${font:+-f "$font"}"
, the semantics change and an empty string is passed to figlet.
来源:https://stackoverflow.com/questions/64941596/bash-logic-inside-command-substitution