Shell 命令重定向输出

Shell 重定向输出到文件
# 将标准输出结果重定向输出到 filelists.text
ls . > filelists.text  

# 将标准输出结果重定向输出追加到 filelists.text
ls . >> filelists.text 

# 将标准输出结果重定向输出到 filelistsstdout.text 
# 将标准错误输出结果重定向输出到 filelistsstderr.text
ls . 1> filelistsstdout.text 2> filelistsstderr.text 

# 将标准输出结果重定向输出到 filelistsstdout.text 
# 将标准错误输出结果重定向输出到标准输出,进而输出到 filelistsstdout.text
ls . 1> filelistsstdout.text 2> &1 

# 将标准输出、标准错误输出结果重定向输出到 filelists.text
ls . &> filelists.text
Shell 重定向输出到管道
cat -n file | grep "searchcharacters"

上面命令将 cat 的结果重定向到管道,并通过管道传给 grep 做筛选,最终输出含有 searchcharacters 的行并带行号

Shell 重定向输出到变量
outputinfostr=$(ls . | tee /dev/tty)

# 使用 printf 或者 echo 打印变量(可打印换行符)
echo -e "$outputinfostr"
printf "$outputinfostr"

上面的命令将 ls 的结果通过管道输入给后面的命令

man tee 可以看到:

The tee utility copies standard input to standard output,
making a copy in zero or more files. The output is unbuffered.

而 /dev/tty 又代表了终端,所以 tee 又把信息输出到终端上显示。这样可以同时输出到变量,而且终端也同样显示。

Stackoverflow 上网友的解说:

/dev/tty is a file system object that represents the current console.
Copying files into this “directory” from the command line prints out > the content of these files to your console

参考:
[1] http://www.360doc.com/content/13/0523/16/7044580_287544243.shtml
[2] http://stackoverflow.com/questions/9139401/trying-to-embed-newline-in-a-variable-in-bash
[3] http://stackoverflow.com/questions/3005963/how-can-i-have-a-newline-in-a-string-in-sh
[4] http://stackoverflow.com/questions/10435308/what-is-dev-tty-in-unix

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值