1. command > filename
将标准输出重定向到一个新的文件中。
2. command >> filename
将标准输出重定向到一个新的文件中(追加)。
3. command 1 > filename
将标准输出重定向到一个文件中。比如,有一个简单输出 hello world 的程序,我们这样执行:$ ./hello 1 > hello.txt
$ cat hello.txt
hello world
4. command > filename 2>&1
现在有一个故意写错的脚本,其内容为:
[Plain Text] 纯文本查看 复制代码 #!/bin/sh
echo "hello world"
if[filename==1]; then
echo "wrong"
fi
exit 0
现在执行上面的命令(执行前,让脚本具有可执行权限)并查看生成的 txt 文件:$ ./error.sh > stdout_and_err.txt 2>&1
$ cat stdout_and_err.txt
hello world
./error.sh: line 5: syntax error near unexpected token `then'
./error.sh: line 5: `if[filename==1]; then' 从上面看到,正确的输出(hello world) 和脚本中后半部的错误信息一起被重定向到相关文件里了。
5. command 2 > filename
把标准错误重定向到 filename 文件中。
6. command 2 >> filename
把标准错误重定向到 filename 文件中(追加)。
7. comand >> filename 2>&1
把标准输出和标准错误一起重定向到一个文件中(追加)。
8. command < filename > filename2
command 命令以 filename 文件作为标准输入,以 filename2 文件作为标准输出。下面用一个程序来说明,程序代码为:
[Plain Text] 纯文本查看 复制代码 #include <stdio.h>
int main()
{
int i;
scanf ("%d", &i);
printf ("hello test1.txt, i get your content %d\n", i);
return (0);
}
同时假设在同一目录下有一个文件 test.txt ,其中内容就只有一个数字: 132 。
现在编译程序后执行以下命令:$ ./hello < test.txt > test2.txt 再查看一下 test2.txt 的内容:$ cat test2.txt
hello test1.txt, i get your content 123 由此可见,hello 程序从 test.txt 中读取了它里面的内容 132,这个值被赋给了 i 这个变量(因为 scanf 函数就是从标准输入中得到值),然后 hello 程序将从 test.txt 中得到的信息导入到 test2.txt 中。
9. command < filename
command 命令以 filename 文件作为标准输入(见8)
10. command << delimiter
从标准输入中读入,直至遇到 delimiter 分界符。下面假设有一个程序,可以读入标准输入内容,程序代码如下:
[Plain Text] 纯文本查看 复制代码 #include <stdio.h>
int main()
{
char a[100];
fgets (a,99,stdin);
printf ("%s\n", a);
return (0);
}
现在这个程序并查看输出:
[beyes@beyes-groad shell]$ ./hello << ,i love linux, and you?
,
i love linux, and you? 上面的操作,分界符是 , 号,所以当输入 i love linux, and you? 换行后输入 , 时,命令马上结束从而输出刚才从标准输入得到的内容。这里需要注意的是,因为在输入 i love linux, and you?时,还输入了回车换行,这个换行操作也被读入到程序中,所以在输出 i love linux, and you? 这一行后,底下会有一空行。
11. command <& m
把文件描述服 m 作为标准输入。
12. command > &m
把标准输出重定向到文件描述符 m 中
13. command < &-
关闭标准输入 |