11input/output

输出重定向

  command1 > file1

  vim test

  hello

  cat test

  who > users

  cat test

  echo "nihao" > test

  cat test

输入重定向

  command1 < file1

  wc -l test  统计行数

重定向深入了解

  一般情况下,每个 Unix/Linux 命令运行时都会打开三个文件:

  • 标准输入文件(stdin):stdin的文件描述符为0,Unix程序默认从stdin读取数据。
  • 标准输出文件(stdout):stdout 的文件描述符为1,Unix程序默认向stdout输出数据。
  • 标准错误文件(stderr):stderr的文件描述符为2,Unix程序会向stderr流中写入错误信息。

  默认情况下,command > file 将 stdout 重定向到 file,command < file 将stdin 重定向到 file。

  如果希望 stderr 重定向到 file,可以这样写:

  command 2 > file

  如果希望 stderr 追加到 file 文件末尾,可以这样写:

  command 2 >> file

  如果希望将 stdout 和 stderr 合并后重定向到 file,可以这样写:

  command > file 2>&1

  command >> file 2>&1

  如果希望对 stdin 和 stdout 都重定向,可以这样写:

  command < file1 >file2

Here Document

  Shell 中的一种特殊的重定向方式,用来将输入重定向到一个交互式 Shell 脚本或程序。

  command << delimiter

    document

  delimiter

  它的作用是将两个 delimiter 之间的内容(document) 作为输入传递给 command。

  注意:

  • 结尾的delimiter 一定要顶格写,前面不能有任何字符,后面也不能有任何字符,包括空格和 tab 缩进。
  • 开始的delimiter前后的空格会被忽略掉。
wc -l << EOF
    欢迎来到
    菜鸟教程
    www.runoob.com
EOF

cat << EOF
欢迎来到
菜鸟教程
www.runoob.com
EOF

/dev/null文件

  如果希望执行某个命令,但又不希望在屏幕上显示输出结果,那么可以将输出重定向到 /dev/null:

  command > /dev/null

  /dev/null 是一个特殊的文件,写入到它的内容都会被丢弃;如果尝试从该文件读取内容,那么什么也读不到。但是 /dev/null 文件非常有用,将命令的输出重定向到它,会起到"禁止输出"的效果。

  如果希望屏蔽 stdout 和 stderr,可以这样写:

  command > /dev/null 2>&1

posted on 2017-10-13 09:11  唐先生_DowneyJr  阅读(266)  评论(0编辑  收藏  举报

导航