命令行从stdin或文件中读取

时间:2017-04-06 20:57:20

标签: linux shell unix command-line

我有一个像这样运行的命令:

$ cmd <file_name> [option]

[option]是可选的,命令可以从stdin读取。所以下面的命令就可以了:

$ cmd file
$ cmd file option
$ cat file | cmd

但是,使用stdin[option]进行阅读会出错:

$ cat file | cmd option
Cannot open file: option

那么如何构造命令,或者我必须将程序改为正确地从stdin读取?

感谢。

1 个答案:

答案 0 :(得分:2)

  1. bash,(以及kshzshyash ......等外壳)中,有process substitution ,它将管道的输出转换为/dev/fd/目录中的 ad hoc 临时文件:

    cmd <(cat file) option
    
  2. 作为R. Sinasohn comments/dev/stdin之类的内容可能会有效:

    cat file | cmd /dev/stdin option
    
  3. 如果命令取决于文件的可写性或具有适当的元数据,那些方法将不会令人满意:

    # No editors:
    sed -i 's/a/A/' <(echo abcd)
    sed: couldn't edit /dev/fd/63: not a regular file
    
    # whatever `file` does won't work.
    file <(echo abcd)
    /dev/fd/63: broken symbolic link to pipe:[15331948]
    
    # file size not the same as data size.
    ls -Hlog <(echo abcd)
    prw------- 1 0 Apr  6 23:27 /dev/fd/63