Linux - 重定向、管道命令

本文介绍Linux系统中的命令行技巧,包括如何利用简单的命令完成复杂任务,重点讲解了管道和重定向机制的应用,以及如何通过这些机制实现命令间的高效协作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

---- 在Linux系统当中,大多数命令都很简单,很少有复杂功能的命令。每个命令往往只实现一个或几个很简单的功能。

---- 我们可以通过将不同功能的命令组合在一起使用,以达到完成某个复杂功能的目的。

---- Linux中,几乎所有命令的返回数据都是纯文本的(因为命令都是运行在CLI - Command line Interface命令行界面下),而纯文本

形式的数据又是绝大多数命令的输入格式,这就让多命令协作称为可能。

---- Linux的命令行为我们提供了管道和重定向机制,多命令协作就是通过管道和重定向完成的。

1、重定向

---- 命令行Shell的数据流有以下定义: 

名称

说明

编号

默认

STDIN

标准输入

0

键盘

STDOUT

标准输出

1

终端

STDERR

标准错误

2

终端

命令通过 STDIN 接收参数或数据,通过 STDOUT 输出结果或通过 STDERR 输出错误

通过管道和重定向,我们可以控制CLI的数据流。

关键字

定义

>(1>)

将STDOUT重定向到文件(覆盖)

>>

将STDOUT重定向到文件(追加)

2>

将STDERR重定向到文件(覆盖)

2>&1

将STDERR与STDOUT结合

(标准错误重定向到标准输出)

<

重定向STDIN

在csh环境下:

> 和 2>: 如果目标文件不存在,则创建文件。如果存在,则覆盖。

[kdvmt@dell:~/shell_test/test]$ ls
[kdvmt@dell:~/shell_test/test]$ echo "hello world" > out
[kdvmt@dell:~/shell_test/test]$ cat out
hello world
[kdvmt@dell:~/shell_test/test]$ echo "a good boy" >> out 
[kdvmt@dell:~/shell_test/test]$ cat out
hello world
a good boy
[kdvmt@dell:~/shell_test/test]$ ls >> out
[kdvmt@dell:~/shell_test/test]$ cat out
hello world
a good boy
out
[kdvmt@dell:~/shell_test/test]$ rm out
[kdvmt@dell:~/shell_test/test]$ ls -l myfile > out
ls: 无法访问'myfile': 没有那个文件或目录
[kdvmt@dell:~/shell_test/test]$ cat out
[kdvmt@dell:~/shell_test/test]$ ls -l myfile 2> out
[kdvmt@dell:~/shell_test/test]$ cat out
ls: 无法访问'myfile': 没有那个文件或目录
[kdvmt@dell:~/shell_test/test]$ mkdir myfile
[kdvmt@dell:~/shell_test/test]$ ls -l myfile/ 2>&1 > out 
[kdvmt@dell:~/shell_test/test]$ cat out
总用量 0
[kdvmt@dell:~/shell_test/test]$ ls -l my >> out 2>&1
[kdvmt@dell:~/shell_test/test]$ cat out 
总用量 0
ls: 无法访问'my': 没有那个文件或目录
[kdvmt@dell:~/shell_test/test]$ date > out
[kdvmt@dell:~/shell_test/test]$ cat out
2023年 12月 14日 星期四 21:03:20 CST
[kdvmt@dell:~/shell_test/test]$ grep root < /etc/passwd
root:x:0:0:root:/root:/bin/bash

将/etc/passwd的内容作为输入给grep命令,来查找root所在的行。

2、管道命令

关键字

定义

|

将一个命令的STDOUT作为另一个命令的STDIN

[yanxia.dong@eslruntime07 exercise]$ ls
file  out  outfile
[yanxia.dong@eslruntime07 exercise]$ ls -l | grep out
-rw-r--r-- 1 yanxia.dong users 29 Apr 15 15:12 out
-rw-r--r-- 1 yanxia.dong users  6 Apr 15 15:22 outfile
[yanxia.dong@eslruntime07 exercise]$ find . -user yanxia.dong | grep file
./file
./outfile
[yanxia.dong@eslruntime07 exercise]$ find . -user yanxia.dong > myout | grep file
[yanxia.dong@eslruntime07 exercise]$ cat myout 
.
./out
./file
./outfile
./myout
[yanxia.dong@eslruntime07 exercise]$ find . -user yanxia.dong | grep file > myout
[yanxia.dong@eslruntime07 exercise]$ cat myout 
./file
./outfile

管道通常用来组合不同的命令,以实现一个复杂的功能。

重定向通常用来保存某命令的输出信息或错误信息。可以用来记录执行结果或保存错误信息到一个指定的文件。(保存log等)

---- script 多个命令的输出都需要记录,可以用script

[yanxia.dong@eslruntime07 ~]$ script
Script started, file is typescript.

我们在启动 script 时没有指定文件名,它会自动记录到当前目录下一个名为 typescript 的文件中。也可以用 -a 参数指定文件名

[yanxia.dong@selruntime07 ~]$ script -a my.txt
Script started, file is my.txt

此时终端的输出内容被记录到 my.txt 这个文件中。

退出 script 时,用 exit 命令。

3、pipe命令创建管道

#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <sys/wait.h>

int main()
{
	pid_t tpid;
	int nfd[2];
	char achbuf[256] = { 0 };
	char* pchw = "hello world\n";
	int nRet = -1;
	nRet = pipe(nfd);//调用成功返回0,失败返回-1
	if( nRet != 0 )
	{
		printf("pipe error\n");
		return -1;
	}
	tpid = fork();
	if( tpid < 0)
	{
		perror("fork error\n");
		return -1;
	}
	else if( tpid == 0 ) //child process
	{
	    printf("child pid = %d\n", getpid());
		close(nfd[1]); //关闭写端
		int nlen = read(nfd[0], achbuf, sizeof(achbuf));
		write(STDOUT_FILENO, achbuf, nlen);
		printf("achbuf = %s\n", achbuf);
		close(nfd[0]);
	}
	else //parent process
	{
		printf("parent pid = %d\n", getpid());
		printf("parent process, tpid = %d\n", tpid);
		close(nfd[0]);//关闭读端
		write(nfd[1], pchw, strlen(pchw));
		wait(NULL);
		close(nfd[1]);
	}
	return 0;
}
kdvmt@kdvmt-dell:dongyanxia$ ./mypipe
achbuf = hello world

### Linux 重定向管道命令的使用教程 #### 一、基本概念 Linux 中的 **重定向** 和 **管道** 是强大的工具,用于控制数据流并增强命令行的功能。通过这些功能,用户可以将标准输入(stdin)、标准输出(stdout)以及错误输出(stderr)重新指向其他位置。 - **重定向** 可以将命令的结果保存到文件中或将文件作为命令的输入。 - **管道** 则允许将一个命令的标准输出连接到另一个命令的标准输入上[^1]。 --- #### 二、重定向符号及其用途 以下是常见的重定向符号及其含义: | 符号 | 描述 | |------------|----------------------------------------------------------------------| | `>` | 将输出覆盖写入指定文件。如果目标文件不存在,则会创建新文件[^1]。 | | `>>` | 将输出追加到指定文件末尾而不删除原有内容[^1]。 | | `<` | 将文件内容作为命令的输入。 | | `2>` | 将错误消息(stderr)写入指定文件[^1]。 | ##### 示例代码: ```bash # 覆盖方式将 ls 命令的输出写入 file.txt ls > file.txt # 追加方式将 echo 的输出添加到 file.txt echo "附加内容" >> file.txt # 使用文件 content.txt 作为 sort 命令的输入 sort < content.txt # 将错误信息写入 error.log grep "pattern" non_existent_file 2> error.log ``` --- #### 三、管道命令的基础用法 **管道符 (`|`)** 用于将前一个命令的输出作为下一个命令的输入。这使得多个命令能够串联起来完成复杂的任务。 ##### 经典案例: ```bash cat /etc/passwd | grep "root" ``` 上述命令先读取 `/etc/passwd` 文件的内容并通过 `grep` 查找包含字符串 `"root"` 的行[^3]。 --- #### 四、高级应用——Tee 命令 当需要同时查看命令输出并将该输出保存到文件时,可使用 `tee` 命令。它不仅转发数据至下一流程,还会将其复制到指定文件中[^2]。 ##### 实例演示: ```bash # 显示 passwd 文件的最后一行,并将整个内容存档于 backup.txt cat /etc/passwd | tee backup.txt | tail -n 1 ``` 此脚本实现了两个目的:一是保留原始数据;二是提取特定部分供后续分析或展示之需。 --- #### 五、结合 Xargs 提升效率 有时单靠管道无法满足需求,这时引入 `xargs` 工具便显得尤为重要。它可以接收来自上游的数据片段,并据此构建新的子进程调用来执行更精细的操作[^3]。 ##### 应用场景举例: 假设要查找当前目录下的所有 `.txt` 文件并对它们逐一计算字数统计: ```bash find . -name "*.txt" | xargs wc -l ``` 这里利用了 find 定位符合条件的目标集合后交由 xargs 来逐项处理每份文档长度测量工作流程。 --- ### 总结 掌握好 Linux 下的重定向管道机制对于提升日常运维效率至关重要。无论是简单的日志记录还是复杂的数据解析链路搭建都离不开这两者的灵活运用^。 问题
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值