Search code examples
zsh

DRYer prompt and assignment in Zsh


I would like to do something that accomplishes the same thing that this does:

[[ -z "$TICKET_NUMBER" ]] && read "TICKET_NUMBER?Ticket Number? "

but that is more condensed, along these lines (but which actually works):

: ${TICKET_NUMBER:=$(read "TICKET_NUMBER?Ticket: ")}

I've looked in the Zsh docs for read to see if there's a way to pass the input to read to STDOUT, but nothing looks like it can do that.

The ideal would be some command that passes the value directly with as little ceremony and repetition as possible. Imagine a get_value command:

: ${TICKET_NUMBER:=$(get_value "Ticket: ")}

Solution

  • The last argument of the previous command is stored in the _ parameter, so you can capture the argument to the -v operator.

    test -v TICKET_NUMBER || read "$_?Ticket? "