电脑技术学习

对话 UNIX: 掌握强大的命令行

dn001

  重定向中的多数操作符在所有的 Unix shell 中已经连续使用了至少 25 年。但是,多数 shell 并没有提供新的特性或采用新方式来应用重定向。例如,多数 shell 只能将输入重定向到单个文件,因此您必须使用如 tee 等实用工具来输出到多个目标。(类似于水管工人使用的 T 型管 (Tee),tee 只支持单个或两个输出。)这里提供一个使用 bash 作为 shell(命令行解释器)的示例:

  清单 5. bash 示例

bash$ ls
tellme
bash$ cat tellme
echo Your current login, working Directory, and system are...
whoami
pwd
systemname
bash$ bash < tellme |& tee log
Your current login and working directory are...
strike
/home/strike
bash: systemname: command not found
bash$ ls
tellme log
bash$ cat log
Your current login and working directory are
strike
/home/strike
bash: systemname: command not found

  尽管 UNIX shell 具有较高的专用性,且通常使用键盘进行交互,但某些 shell 如 bash 等也能从文件读取输入内容。(实际上,stdin 也是一种文件。)在前面的片段中,短语 bash < commands 告诉 bash 执行在文件 tellme 中找到的命令列表。短语 |&tee log 将 bash 的 stdout 和 stderrto 通过管道重定向到 tee 实用工具,后者将其 stdin 打印到 stdout 和 文件 log 中。

  但是,如果您打算使用 bash 来处理多个文件,该怎么办呢?cat file1 file2 file3 | bash 是一种可行的方法,这也许也是唯一的一种方法,因为在 bash 中并不支持如 bash < file1 < file2 < file3 的语法。

标签: