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