Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Of course you can do this sort of thing,

read var; if [[ $var = 'y' ]]; then echo "Yes"; fi

But is there any way to skip the first step and do something a little more like this, (ideally without needing a subshell):

if [[ $(read var) = 'y' ]]; then echo "Yes"; fi

Of course the above doesn't work unless you add echo, but I'm looking for something much cleaner and simpler than this:

if [[ $(read var; echo "$var") = 'y' ]]; then echo "Yes"; fi

It would be ideal if this would work:

if [[ read = 'y' ]]; then echo "Yes"; fi
share|improve this question
read && printf '\a' is pretty succinct and is bound to make your application a popular one. – mikeserv Aug 1 '14 at 20:26
up vote 3 down vote accepted

How about using a function to do what you need:

user_input () {
    read var
    echo $var
if [ "$(user_input)" = 'y' ]; then echo "Yes"; fi

At the top I define a function called user_input, which will read the value in, and then echo it out. Then the if statement is able to take that value and check if it is 'y'. I've wrapped the $(user_input) in quotation marks in case the user put in spaces, so that the script doesn't just error out.

share|improve this answer
Yes: if I change the name of the function to something like user_input then the resulting code reads quite nicely. – iconoclast Aug 1 '14 at 22:03

Not sure if this is still too long for what you had in mind:

read foo && [ "$foo" = 'y' ] && echo 'Yes'
share|improve this answer

With zsh:

read -q && echo yes

(see also -s to suppress the echo of the y or n you type).

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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