如何在Nushell脚本中访问stdin(标准输入)?
在Nushell中处理管道输入(v0.112.1)
Nushell 里没有 $stdin 这个变量,要处理管道输入得用内置的 stdin 命令,下面给你几种常用的实现方式:
读取全部输入为单个字符串
如果要把管道传递的内容当作完整的原始字符串处理,在脚本里加上--raw参数:# mynuscript.nu let input = stdin --raw print $input describe $input执行
echo one two three | nu mynuscript.nu,会输出输入的字符串,describe会返回string类型。按行读取并处理输入
要是管道过来的是多行内容,比如从文件读取后传递,可以结合lines命令拆分每行:# mynuscript.nu stdin | lines | enumerate | each { |line| print $"Line ($line.index + 1): ($line.item)" }比如执行
echo -e "first\nsecond\nthird" | nu mynuscript.nu,会逐行带编号输出内容。处理结构化输入
Nushell 支持传递结构化数据(比如表格),直接用stdin就能接收解析后的结构:# mynuscript.nu let structured_input = stdin print $structured_input describe $structured_input执行
ls | nu mynuscript.nu,describe会返回table类型,你可以直接操作表格里的字段(比如$structured_input.name)。
补充:不加 --raw 的 stdin 会自动尝试解析输入为 Nushell 能识别的数据类型,比如数字、列表、表格等;如果不需要解析,就用 stdin --raw 保持原始字符串。
内容的提问来源于stack exchange,提问作者Pirx
相关产品推荐
相关产品推荐

