Send string to stdin

前端 未结 6 1668
北海茫月
北海茫月 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条回答
  •  死守一世寂寞
    2020-11-27 10:08

    Solution

    You want to (1) create stdout output in one process (like echo '…') and (2) redirect that output to stdin input of another process but (3) without the use of the bash pipe mechanism. Here's a solution that matches all three conditions:

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

    The < is normal input redirection for stdin. The <(…) is bash process substitution. Roughly it creates a /dev/fd/… file with the output of the substituting command and passes that filename in place of the <(…), resulting here for example in script < /dev/fd/123. For details, see this answer.

    Comparison with other solutions

    • A one-line heredoc sent to stdin script <<< 'string' only allows to send static strings, not the output of other commands.

    • Process substitution alone, such as in diff <(ls /bin) <(ls /usr/bin), does not send anything to stdin. Instead, the process output is saved into a file, and its path is passed as a command line argument. For the above example, this is equivalent to diff /dev/fd/10 /dev/fd/11, a command where diff receives no input from stdin.

    Use cases

    I like that, unlike the pipe mechanism, the < <(…) mechanism allows to put the command first and all input after it, as is the standard for input from command line options.

    However, beyond commandline aesthetics, there are some cases where a pipe mechanism cannot be used. For example, when a certain command has to be provided as argument to another command, such as in this example with sshpass.

提交回复
热议问题