【问题标题】:how do you make `nix-shell` read from stdin?你如何让“nix-shell”从标准输入中读取?
【发布时间】:2020-07-03 14:53:15
【问题描述】:

交互式程序通常可以从标准输入读取输入,例如,

$ echo echo hello | bash
hello

$ echo 1 2 + p | dc
3

但是,nix-shell 似乎没有这种行为,例如

$ echo hello | nix-shell -p  hello
$

而预期的输出应该是Hello, world!

使用nix-shell(1)中建议的技巧:

       --command cmd
           In the environment of the derivation, run the shell command cmd. This command is executed in an
           interactive shell. (Use --run to use a non-interactive shell instead.) However, a call to exit is
           implicitly added to the command, so the shell will exit after running the command. To prevent
           this, add return at the end; e.g.  --command "echo Hello; return" will print Hello and then drop
           you into the interactive shell. This can be useful for doing any additional initialisation.

导致错误:

$ echo hello | nix-shell -p  hello --command return
/tmp/nix-shell-15399-0/rc: line 1: return: can only `return' from a function or sourced script
$

我的相关程序版本如下:

$ nix --version
nix (Nix) 2.3.2
$ bash --version
GNU bash, version 4.4.23(1)-release (x86_64-pc-linux-gnu)
$ 

因此我的问题是:我如何让nix-shell 从标准输入中读取,例如bashdc

【问题讨论】:

    标签: bash shell nix nix-shell


    【解决方案1】:

    不像它的名字可能暗示的那样,nix-shell 不是典型的 UNIX 意义上的 shell;只是广义上是一个启动程序的程序。

    -p 参数仅用于将软件引入 shell 环境。您可以使用多个,但它们并没有实际运行这些程序的效果*。

    要让nix-shell启动bash,不管nix-shell自己的逻辑如何,例如使用:

    $ echo hello | nix-shell -p hello --run bash
    Hello, world!
    

    【讨论】:

    • 感谢您的回答,但这并不能解决我的问题。让我澄清一下:我只是将-p hello 用作假人。在我的应用程序中,我有一个shell.nix 文件,其中包含一个相当复杂的shellHook 脚本(具有内部状态)。这在交互运行时完美运行,即,我可以运行由shellHook 定义的函数非常好。现在我需要通过管道命令到nix-shell 来做同样的事情,而不是手动输入它们。按照一般的 Unix 哲学,这应该可行。为什么不呢?是不是因为nix-shell 太聪明了,猜测它是否连接到终端?
    • 特别注意--run bash对我没有用,我需要管道将命令输入到执行shellHook的同一个解释器中。
    • 试试echo hello | nix-shell -p hello --command 'source /dev/stdin',请酌情使用大写字母。考虑到您是在求人,您不仅会显得懒惰,而且会不体贴和粗鲁。你只是让任何人都更难履行这个恩惠。使用此建议对您有利;无需回复。
    猜你喜欢
    • 2010-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多