
Bash에서 다음 구문을 사용할 수 있다는 것을 알고 있습니다.
editor=${new_editor:-/usr/bin/vi}
변수가 비어 있지 않으면 editor
으로 설정되고, 그렇지 않으면 으로 설정됩니다. 특정 명령의 출력으로 설정하고 출력이 비어 있는 경우 일부 기본값으로 설정하는 유사한 한 줄의 코드를 생성할 수 있습니까? 이와 같은 것(예를 들어, 이것은 작동하지 않습니다)new_editor
new_editor
/usr/bin/vi
editor
editor=$( $(which emacs) :-/usr/bin/vi )
몇 줄의 코드로 이를 수행하는 방법을 알고 있지만 우아한 솔루션이 있는지 궁금합니다.
답변1
앞쪽:
$ : "${editor:=$(command -v emacs)}" "${editor:=/usr/bin/vi}"
$ printf '%s\n' "$editor"
emacs
그러나 Bourne과 유사한 쉘에서는 중첩된 매개변수 확장을 수행할 수 없습니다 zsh
.
$ editor=${$(whence -p emacs):-/usr/bin/vi}
$ print -rl -- $editor
/usr/bin/emacs
또는:
editor=${commands[emacs]-$commands[vi]}