5

This question already has an answer here:

I have a bash script that is named reader. It reads user input:

#!/bin/bash
read -p "What is your name?" username
echo "Hello, ${username}"

Running the script by source reader (EDIT: from the zsh shell), I get the error reader:read:2: -p: no coprocess. It doesn't give this error when I run it as ./reader.

Other read options do not produce this error. For example, I could have done:

#/bin/bash
echo -n "What is your name?"
read username
echo "Hello, ${username}"

Where does the no coprocess error come from? What does it mean? And what should I do about it?

marked as duplicate by Kusalananda, countermode, GAD3R, Archemar, user181255 Feb 22 '17 at 10:49

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

3

When you use source, it's the current shell that reads the file, not the shell mentioned on the #! line. And I assume that your shell is either zsh or ksh93 which uses read -p to read from a co-process.

An example of that in ksh93:

cat /etc/passwd |&

while IFS=":" read -p user rest; do
    printf 'There is a user called %s\n' "$user"
done

To run your script, either explicitly mention the interpreter:

$ bash script.sh

... or make the script executable and run it:

$ chmod +x script.sh
$ ./script.sh

To get read to use a custom prompt in both zsh and ksh93:

read username"?What's you name? " 
printf 'Hello %s!\n' "$username"
  • Actually, I was using the zsh shell. I edited my question to show this crucial fact. I found that zsh also uses -p to read from a coprocess. – Flux Feb 22 '17 at 2:27
  • @Flux, ah, yes that makes sense too. – Kusalananda Feb 22 '17 at 7:15
  • @Flux I've updated the answer a tiny bit, but also marked the question as a duplicate. The main issue was the sourcing of the script in any case. – Kusalananda Feb 22 '17 at 7:23

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