- 常用重定向
shiyanlou:~/ $ echo 'hello shiyanlou' > redirect
shiyanlou:~/ $ echo 'www.shiyanlou.com' >> redirect
shiyanlou:~/ $ cat redirect
hello shiyanlou
www.shiyanlou.com
- 简单重定向
- 将一个文件作为命令的输入,标准输出作为命令的输出:
cat Documents/test.c
- 将 echo 命令通过管道传过来的数据作为 cat 命令的输入,将标准输出作为命令的输出:
echo 'hi' | cat
- 将 echo 命令的输出从默认的标准输出重定向到一个普通文件:
echo 'hello shiyanlou' > redirect
cat redirect
- 标准错误重定向
cat Documents/test.c hello.c > somefile
# 将标准错误重定向到标准输出,再将标准输出重定向到文件,注意要将重定向到文件写到前面
cat Documents/test.c hello.c >somefile 2>&1
# 或者只用bash提供的特殊的重定向符号"&"将标准错误和标准输出同时重定向到文件
cat Documents/test.c hello.c &>somefilehell
- 使用tee命令同时重定向到多个文件
shiyanlou:~/ $ echo 'hello shiyanlou' | tee hello
hello shiyanlou
shiyanlou:~/ $ cat hello
hello shiyanlou
- 永久重定向
- 使用
exec命令实现永久重定向。exec命令的作用是使用指定的命令替换当前的 Shell,即使用一个进程替换当前进程,或者指定新的重定向:
# 先开启一个子 Shell
zsh
# 使用exec替换当前进程的重定向,将标准输出重定向到一个文件
exec 1>somefile
# 后面执行的命令的输出都将被重定向到文件中,直到退出当前子shell,或取消exec的重定向
ls
exit
cat somefile
- 创建输出文件描述符
cd /dev/fd/;ls -Al
zsh
exec 3>somefile
cd /dev/fd/;ls -Al;cd -
echo "this is test" >&3
cat somefile
exit
- 关闭文件描述符
exec 3>&-
cd /dev/fd;ls -Al;cd -
- 完全屏蔽命令的输出
cat Documents/test.c 1>/dev/null 2>&1
- 使用xargs分割参数列表