pipe tail output into another script

前端 未结 3 1843
滥情空心
滥情空心 2021-02-06 02:06

I am trying to pipe the output of a tail command into another bash script to process:

tail -n +1 -f your_log_file | myscript.sh

However, when I

3条回答
  •  野性不改
    2021-02-06 02:52

    Generally, here is one way to handle standard input to a script:

    #!/bin/bash
    
    while read line; do
        echo $line
    done
    

    That is a very rough bash equivalent to cat. It does demonstrate a key fact: each command inside the script inherits its standard input from the shell, so you don't really need to do anything special to get access to the data coming in. read takes its input from the shell, which (in your case) is getting its input from the tail process connected to it via the pipe.

    As another example, consider this script; we'll call it 'mygrep.sh'.

    #!/bin/bash
    
    grep "$1"
    

    Now the pipeline

    some-text-producing-command | ./mygrep.sh bob
    

    behaves identically to

    some-text-producing-command | grep bob
    

    $1 is set if you call your script like this:

    ./myscript.sh foo
    

    Then $1 has the value "foo".

    The positional parameters and standard input are separate; you could do this

    tail -n +1 -f your_log_file | myscript.sh foo
    

    Now standard input is still coming from the tail process, and $1 is still set to 'foo'.

提交回复
热议问题