1

Straight to the point, I have a script that will read user input and interactively prompts before printing the final output which is expected to be obtainable by the calling user like so:

AVAR=$(myscript arg1 arg2 arg3)

So I came up with a dirty[?] hack[?] in myscript:

# ... blah ...
echo -n "A prompt for the user " >> /dev/stderr
read SOMEVAR >> /dev/null
# ... other stuff ...
printf "Results\t$RESULT\n"

Is this some sort of evil, bad practice using stderr or am I just being resourcefully sly? Excuse my ignorance, I'm 100% self-taught so I'm using deductive reasoning, ie, everything I don't want in the caller's variable must be redirected, but in the case of prompts, it still needs to be displayed, and stderr was are I could come up with.

  • 4
    It is usually bad practice to prompt the user. Why would you want to do that instead of having the user provide the input as an argument? That will both solve your redirection issue and allow your script to be automated. – terdon Dec 6 '16 at 12:32
  • 4
    It's also a bad practice to redirect stdout to stderr with >> /dev/stderr instead of the common >&2. Many systems don't even have a /dev/stderr. – Satō Katsura Dec 6 '16 at 12:34
  • @SatoKatsura Thank you so much for bringing that to my attention. I actually don't recall much about those caveats so I'm going to have another read through the basics now, before I mess anything up. – nonzyro Dec 6 '16 at 12:58
  • @terdon The idea I was going for was a re-usable fragment for scripts where I could, say prompt the user with multiple questions and have the results returned in a single call, that's why I need prompts (reinventing the wheel). – nonzyro Dec 6 '16 at 12:59
  • 1
    @nonzyro that's no reason to prompt the user. Prompting for anything more than a single character is risky since typos are very easy and a pain in the neck since your user can't repeat the same command but needs to laboriously type out their input every time. There are valid use cases but, in my experience, 9 times out of 10 when you think of prompting, you shouldn't. – terdon Dec 6 '16 at 13:10
1

Solved: Yes, this is bad practice. Thanks @SatoKatsura for filling in the blanks.

The correct thing to do is:

# ... blah ...
echo -n "A prompt for the user " >&2
read SOMEVAR >> /dev/null
# ... other stuff ...
printf "Results\t$RESULT\n"

Which is portable and better, safer practice.

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.