Using read -p in a bash script that was executed from pipe

后端 未结 2 1101
予麋鹿
予麋鹿 2021-01-13 02:37

I apologize in advance - I don\'t fully understand the ideas behind what I\'m asking well enough to understand why it\'s not working (I don\'t know what I need to le

2条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-13 03:12

    The main reason why this is not working is, as the OP validly indicated,

    • The | which is used, sends the standard output from the first command as standard input to the second command. In this case, the first command is

      wget -q -O - http://myscript.sh
      

      which passes a downloaded script via the pipe to its interpreter bash

    • The read statement in the script uses the same standard input to obtain its value.

    So this is where it collapses because read is not awaiting input from you but takes it from its own script. Example:

    $ cat - < set -x
    > read p
    > somecommand
    > echo \$p
    > EOF
    + read p
    + echo somecommand
    somecommand
    

    In this example, I used a here-document which is piped to bash. The script enables debugging using set -x to show what is happening. As you see, somecommand is never executed but actually read by read and stored in the variable p which is then outputted by echo (note, the $ has been escaped to avoid the substitution in the here-document).

    So how can we get this to work then?

    First of, never pipe to an interpreter such as {ba,k,z,c,tc,}sh. It is ugly and should be avoided, even though it feels the natural thing to do. The better thing to do is to use any of its options:

    bash -c string: If the -c option is present, then commands are read from string. If there are arguments after the string, they are assigned to the positional parameters, starting with $0.

    $ bash -c "$(command you want to pipe)"
    

    This also works for zsh, csh, tcsh, ksh, sh and probably a lot of others.

提交回复
热议问题