2

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.

1 Answer 1

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]}
2
  • 1
    For the first one, ITYM : "${editor:=$(command -v emacs)}" "${editor:=/usr/bin/vi}" (assuming $editor was previously empty/unset) Nov 24, 2016 at 14:31
  • 2
    In zsh, see also editor=${commands[emacs]-$commands[vi]} Nov 24, 2016 at 14:33

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .