1

I have a little zsh script for prompting the user for some input:

#!/usr/bin/env zsh
IFS="$(printf "\n\t")"
printf "${1-query}: " 1>&2
read -r query
echo "${query}"

If I type something at the prompt then try to use the arrow keys to go back and edit, I get ^[[D instead. My TERM env is xterm. How can I get the arrow keys working properly for line editing as if this was a regular zsh command line?

Here's the output of setopt in case any of these are relevant:

emacs
noflowcontrol
histexpiredupsfirst
histfindnodups
histignorealldups
histignoredups
histsavenodups
histverify
incappendhistory
interactive
interactivecomments
monitor
nonomatch
promptsubst
shinstdin
zle
2

1 Answer 1

2

Based on a comment linking to this answer, I learned about vared. Here's what I used which works great:

#!/usr/bin/env zsh
IFS="$(printf "\n\t")"
query=
vared -p "${1-query}: " query 
echo "${query}"
3
  • 1
    You'd use IFS=$'\n\t' to set IFS to newline and tab. However here your code doesn't use $IFS. Commented Mar 25, 2019 at 10:30
  • You'd also need echo -E - "$query" for echo to output the content of $query verbatim. Or the more portable: print -r -- "$query" like in ksh or even better printf '%s\n' "$query" (POSIX) Commented Mar 25, 2019 at 11:04
  • vared wont work inside subshells, try vared -c variable vs ( vared -c variable ). To solve spawn a new zsh process like this: variable=$(declare read_return_status; vared -c input; read_return_status="$?"; printf "%s" "$input"; exit "$read_return_status" )" that way you also keep the read return status to detect read failures.
    – Zeta
    Commented Sep 30, 2020 at 22:29

You must log in to answer this question.

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