Linux命令行与shell脚本(11)--输入/输出重定向

理解输入和输出

  • 重定向错误消息
    ls -al badfile 2> test4
  • 重定向错误和数据
    ls -al test test2 test3 badtest 2> test6 1> test7 #错误输入到test6,正常数据显示到test7
  • ls -al test test2 &> test8 #将标准错误和标准输入都重定向到test8

在脚本中重定向输出

  • 将文本输出到标准错误中 echo "This is an error message" >&2
  • 可以使用 exec 命令告诉shell脚本在执行期间重定向某个特定文件描述符
echo "This is the start of the script";
echo "now redirecting all output to another location";

exec 1> testout
exec 2> testerror

echo "This output should go to the testout file";
echo "This output should go to the testerror file" >&2;

在脚本中重定向输入

  • exec命令允许将STDIN重定向到Linux系统上的文件中
file="/Users/chenhong/Desktop/shell_workspace/STD.sh";
exec 0< $file
count=1
while read line
do
        echo "Line $count:$line";
        count=$[ $count + 1 ];
done

创建自己的重定向

  • 可以使用exec命令来输出分配文件描述符
exec 3>testout # 也可以使用 exec 3>>testout 进行追加
echo "This shoud output the STDOUT";
echo "This shoud output the &3" >&3;
  • 要关闭文件描述符,将它重定向到特殊符号&- exec 3>&-

列出打开的文件描述符

  • 显示当前进程的默认文件描述符 lsof -a -p $$ -d 0,1,2

阻止命令输出

  • shell输出到null文件的任何数据都不会保存,这样它们就都被丢掉了 ls -al > /dev/null
  • 可以用它快速移除现有文件中的数据而不用先删除文件再创建 cat /dev/null > testfile

记录消息

  • tee命令相当于管道的一个T型接头。它将从STDIN过来的数据同时发给两个目的地。一个目的地是STDOUT,另一个目的地是tee命令行所指定的文件名 date | tee testout
  • 默认情况下,tee每次都会覆盖文件,追加文件,可以使用-a date | tee -a testout
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值