Reading input while also piping a script via stdin

后端 未结 2 1824
隐瞒了意图╮
隐瞒了意图╮ 2021-01-22 05:14

I have a simple Bash script:

#!/usr/bin/env bash
read X
echo \"X=$X\"

When I execute it with ./myscript.sh it works. But when I ex

相关标签:
2条回答
  • 2021-01-22 06:08

    Instead of just running

    read X
    

    ...instead replace it with...

    read X </dev/tty || {
      X="some default because we can't read from the TTY here"
    }
    

    ...if you want to read from the console. Of course, this only works if you have a /dev/tty, but if you wanted to do something robust, you wouldn't be piping from curl into a shell. :)


    Another alternative, of course, is to pass in your value of X on the command line.

    curl https://some.place/with-untrusted-code-only-idiots-will-run-without-reading \
      | bash -s "value of X here"
    

    ...and refer to "$1" in your script when you want X.

    (By the way, I sure hope you're at least using SSL for this, rather than advising people to run code they download over plain HTTP with no out-of-band validation step. Lots of people do it, sure, but that's making sites they download from -- like rvm.io -- big targets. Big, easy-to-man-in-the-middle-or-DNS-hijack targets).

    0 讨论(0)
  • 2021-01-22 06:15

    When you cat a script to bash the code to execute is coming from standard input.

    Where does read read from? That's right also standard input. This is why you can cat input to programs that take standard input (like sed, awk, etc.).

    So you are not running "a script" per-se when you do this. You are running a series of input lines.

    Where would you like read to read data from in this setup?

    You can manually do that (if you can define such a place). Alternatively you can stop running your script like this.

    0 讨论(0)
提交回复
热议问题