23

I want to write this bash loop for zsh

while true; do echo "print something"; read -p "pause"; done

This loop echos, then waits for the user to press enter. If I enter it as is, the read statement doesn't pause, causing zsh to infinitely echo "print something" without waiting for the user to press enter.

0

6 Answers 6

39

In zsh:

read -s -k '?Press any key to continue.'

From man zshbuiltins:

  • -s Don't echo back characters if reading from the terminal.
  • -k Read only one character.
  • name?prompt Name is omitted, thus user input is stored in the REPLY variable (and we ignore it). The first argument contains a ?, thus the remainder of this word is used as a prompt on standard error when the shell is interactive.

To include a newline after the prompt:

read -s -k $'?Press any key to continue.\n'

$'' is explained under QUOTING in man zshmisc.

Finally, a pause function that takes an arbitrary prompt message in a script that does what the OP asks:

#!/usr/bin/env zsh

pause() read -s -k "?$*"$'\n'

while true; do
    echo "print something"
    pause "pause"
done
13

Since this is about the only search result I could find, and I found it helpful but still a bit confusing, here is another way of putting it: If all you want to do is echo a line of text and wait for the user to press enter ... read \?"I am waiting for you to press [Enter] before I continue."

11

It looks like -p does something different in zsh. You will probably need something like read some_variable\?pause.

1
  • Using _ doesn't work: zsh throws an error zsh: read-only variable: _ . Anything else works though. Thanks for the tip.
    – k107
    Commented Mar 7, 2011 at 3:17
1
#!/bin/zsh

pause()
{
    echo "$*"; read -k1 -s
}

now we can call the function with any prompt text:

pause "paused! press any key to continue"
pause "you can write anything here :)"
1

If you want a way that works in both bash and zsh, and ensures I/O to/from the terminal:

# Prompt for a keypress to continue. Customise prompt with $*
function pause {
  >/dev/tty printf '%s' "${*:-Press any key to continue... }"
  [[ $ZSH_VERSION ]] && read -krs  # Use -u0 to read from STDIN
  [[ $BASH_VERSION ]] && </dev/tty read -rsn1
  printf '\n'
}
export_function pause
0

This works in zsh and bash:

printf >&2 '%s ' 'Press any key to continue ...'
read ans

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.