Send string to stdin

前端 未结 6 1663
北海茫月
北海茫月 2020-11-27 09:48

Is there a way to effectively do this in bash:

/my/bash/script < echo \'This string will be sent to stdin.\'

I\'m aware that I could pip

6条回答
  •  -上瘾入骨i
    2020-11-27 10:17

    aliases can and can't process piped stdin...

    Here we create 3 lines of output

    $ echo -e "line 1\nline 2\nline 3"
    line 1
    line 2
    line 3
    

    We then pipe the output to stdin of the sed command to put them all on one line

    $ echo -e "line 1\nline 2\nline 3" |  sed -e ":a;N;\$!ba ;s?\n? ?g"
    line 1 line 2 line 3
    

    If we define an alias of the same sed command

    $ alias oline='sed -e ":a;N;\$!ba ;s?\n? ?g"'
    

    We can pipe the output to the stdin of the alias and it behaves exactly the same

    $ echo -e "line 1\nline 2\nline 3" |  oline
    line 1 line 2 line 3
    

    The problem arises when we try to define the alias as a function

    $ alias oline='function _oline(){ sed -e ":a;N;\$!ba ;s?\n? ?g";}_oline'
    

    Defining the alias as a funstion breaks the pipe

    $ echo -e "line 1\nline 2\nline 3" |  oline
    >
    

提交回复
热议问题