在读取输入的同时还通过stdin传递脚本 [英] Reading input while also piping a script via stdin

查看:91
本文介绍了在读取输入的同时还通过stdin传递脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的Bash脚本:

I have a simple Bash script:

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

当我用./myscript.sh执行它时,它可以工作.但是,当我使用cat myscript.sh | bash执行它时,实际上会将echo "X=$X"放入$X.

When I execute it with ./myscript.sh it works. But when I execute it with cat myscript.sh | bash it actually puts echo "X=$X" into $X.

因此,此脚本会打印用cat myscript.sh | bash执行的 Hello World :

So this script prints Hello World executed with cat myscript.sh | bash:

#!/usr/bin/env bash
read X
hello world
echo "$X"

  • cat myscript.sh | bash执行脚本有什么好处?为什么不做与使用./myscript.sh执行它一样的事情?
  • 如何避免Bash逐行执行,而是在STDIN结束后执行所有行?
    • What's the benefit of executing a script with cat myscript.sh | bash? Why doesn't do it the same things as if I execute it with ./myscript.sh?
    • How can I avoid Bash to execute line by line but execute all lines after the STDIN reached the end?
    • 推荐答案

      而不是仅仅运行

      read X
      

      ...相反,将其替换为...

      ...instead replace it with...

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

      ...如果要从控制台读取.当然,这只有在拥有 /dev/tty的情况下才有效,但是如果您想做一些健壮的事情,就不会将curl从管道输送到外壳中. :)

      ...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. :)

      当然,另一种选择是在命令行中传递X的值.

      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"
      

      ...,并在需要X时在脚本中引用"$1".

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

      (顺便说一句,我当然希望您至少为此使用SSL,而不是建议人们运行他们通过纯HTTP下载的代码,而没有带外验证步骤. ,但是这使得他们从[c12]这样的网站上下载了大型目标.易于使用的大型中间人或DNS劫持目标).

      (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).

      这篇关于在读取输入的同时还通过stdin传递脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆