0

I know that in Bash you can use the syntax

editor=${new_editor:-/usr/bin/vi}

which will set editor to new_editor if the variable new_editor is not empty and to /usr/bin/vi otherwise. Is it possible to produce similar one-liner, which will set editor to output of some command and to some default value if the output is empty? Something like (only as example, this does not work)

editor=$( $(which emacs) :-/usr/bin/vi )

I know how to do it in several lines of code, but would like to know if an elegant solution exists.

2

POSIXLY:

$ : "${editor:=$(command -v emacs)}" "${editor:=/usr/bin/vi}"
$ printf '%s\n' "$editor"
emacs

You can't do nested parameter expansion in any Bourne-like shells but zsh:

$ editor=${$(whence -p emacs):-/usr/bin/vi}
$ print -rl -- $editor
/usr/bin/emacs

or:

editor=${commands[emacs]-$commands[vi]}
  • 1
    For the first one, ITYM : "${editor:=$(command -v emacs)}" "${editor:=/usr/bin/vi}" (assuming $editor was previously empty/unset) – Stéphane Chazelas Nov 24 '16 at 14:31
  • 2
    In zsh, see also editor=${commands[emacs]-$commands[vi]} – Stéphane Chazelas Nov 24 '16 at 14:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.