0

I have the following bash script, saved as script.sh:

echo "Do that? [Y,n]"
read input
if [[ $input == "Y" || $input == "y" ]]; then
        echo "do that"
else
        echo "don't do that"
fi

On the terminal, I would like to run the script together with input in a single line. I attempted

./trial.sh < y

However, I receive the following output

bash: y: No such file or directory

How can I resolve this?

1
  • If you write <foo, you are redirecting from a file named foo. In your case, a file named y would be needed. The file does not exist, and hence the error message. Commented Oct 29, 2019 at 6:54

2 Answers 2

2

Redirection with < expects a filename to read standard input from. You could

  • use a here-doc:

    ./trial.sh <<'EOF'
    y
    EOF
    
  • use a here-string:

    ./trial.sh <<< y
    
  • print a y and send it to standard input with a pipe:

    printf 'y' | ./trial.sh
    
  • or use the yes tool, which does exactly that:

    yes | ./trial.sh
    

    yes can also send other strings: yes n prints n instead of y.


Side note: your script can be shortened to

read -rp "Do that? [Y,n] " input
if [[ $input == [Yy] ]]; then
    echo "do that"
else
    echo "don't do that"
fi
Sign up to request clarification or add additional context in comments.

Comments

1

When you redirect stdin using the < the next token on the command line is expected to be a filename -- thus the error message...

Instead, try "piping" the Input string "y" into your command, like so:

echo "y" | ./script.sh

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.