Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read input from the user in a bash subshell [duplicate]

Consider this bash script :

#!/bin/bash
while true; do
    read -p "Give me an answer ? y/n : " yn
    case $yn in
        [Yy]* ) answer=true ; break;;
        [Nn]* ) answer=false ; break;;
        * ) echo "Please answer yes or no.";;
    esac
  done

if $answer 
  then 
    echo "Doing something as you answered yes"
      else 
    echo "Not doing anything as you answered no" 
fi

When run from the command line using :

$ ./script-name.sh

It works just as expected with the script waiting for you to answer y or n.

However when I upload to a url and attempt to run it using :

$ curl http://path.to/script-name.sh | bash

I get stuck in a permanent loop with the script saying Please answer yes or no. Apparently the script is receiving some sort of input other than y or n.

Why is this? And more importantly how can I achieve user input from a bash script called from a url?

like image 206
dwkns Avatar asked Nov 24 '22 04:11

dwkns


2 Answers

Perhaps use an explicit local redirect:

read answer < /dev/tty
like image 115
Scrutinizer Avatar answered Nov 29 '22 07:11

Scrutinizer


You can run it like this:

bash -c "$(curl -s http://path.to/script-name.sh)"

Since you're supplying content of bash script to bash interpreter. Use curl -s for silent execution.

like image 34
anubhava Avatar answered Nov 29 '22 06:11

anubhava