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

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}"
  • 1
    You'd use IFS=$'\n\t' to set IFS to newline and tab. However here your code doesn't use $IFS. – Stéphane Chazelas Mar 25 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) – Stéphane Chazelas Mar 25 at 11:04

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.