【问题标题】:From within a shell script I want to access input given from other command从 shell 脚本中,我想访问从其他命令给出的输入
【发布时间】:2020-01-12 15:39:04
【问题描述】:

我在搞乱 shell 脚本,我试图让我的脚本从另一个命令(比如 ls)中获取输入。它是这样调用的:

ls | ./example.sh

我尝试从 example.sh 中访问输入

#!/bin/bash
echo $1

但它没有回声。有没有另一种方法来引用其他命令给 bash 的参数,因为如果我输入它就可以工作:

./example.sh poo

【问题讨论】:

    标签: bash shell redirect input output


    【解决方案1】:

    参数和输入不是一回事:

    $ ls
    example.sh  foo
    $
    $ cat example.sh
    for param; do
        printf 'argument 1: "%s"\n' "$param"
    done
    
    while IFS= read -t 1 -r input; do
        printf 'input line: "%s"\n' "$input"
    done
    $
    $ ls | ./example.sh
    input line: "example.sh"
    input line: "foo"
    $
    $ ls | ./example.sh bar
    argument 1: "bar"
    input line: "example.sh"
    input line: "foo"
    $
    $ ./example.sh $(ls)
    argument 1: "example.sh"
    argument 1: "foo"
    

    参数是传递给脚本以开始运行的参数,输入是脚本在运行时读取的内容。

    【讨论】:

      【解决方案2】:

      您可以使用 xargs 来执行此操作。

      ls | xargs ./example.sh
      

      资源

      https://ss64.com/bash/xargs.html

      https://www.cyberciti.biz/faq/linux-unix-bsd-xargs-construct-argument-lists-utility/

      或阅读手册页

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-02-27
        • 2018-07-29
        相关资源
        最近更新 更多