管道符("|")
将前面命令的输出作为后面命令的输入。 可以使用多个管道符连接多条命令。
# 输出字符串'hello world'给wc命令进行单词数量统计
echo "hello world" | wc -w
# 输出:
2
输出重定向符(">")
将命令的输出重定向到文件中。 重定向解释:一般程序会输出到标准输出stdout,通常是正在使用的终端,重定向符将标准输出重定向到标准输出以外的地方。
# 将字符串hello world重定向(写入)到文件hello.txt中
# 如果文件不存在,则创建文件;如果文件存在,则覆盖文件内容
echo "hello world" > hello.txt
# 输出hello.txt文件内容
cat hello.txt
# 输出:
hello world
追加重定向符(">>")
将命令的输出追加到文件中。
# 将字符串hello world追加到文件hello.txt中
# 如果文件不存在,则创建文件;如果文件存在,则追加内容到文件末尾
echo "hello world" >> hello.txt
# 输出hello.txt文件内容
cat hello.txt
# 输出:
hello world
hello world
echo命令输出默认为一行,所以输出内容末尾自带换行符。
输入重定向符("<")
将文件作为命令的输入。
echo "hello world" > hello.txt
# 将文件hello.txt作为wc命令的输入
wc -w < hello.txt
# 输出:
2
多行输入重定向符("<<")
又叫 Here Document,将多行字符串作为命令的输入。
# 将多行字符串作为wc命令的输入
# 用EOF(end of file)作为结束标志是惯例,可以用其他的。
# EOF前后不能有任何字符或空格。
wc -w << EOF
> hello world
> hello world
> EOF
# 输出:
4
特殊重定向符号
程序运行会打开以下三个文件:
标准输入文件(stdin)
stdin 的文件描述符为 0,程序默认从 stdin 读取数据。
标准输出文件(stdout)
stdout 的文件描述符为 1,程序默认向 stdout 输出数据。
标准错误文件(stderr)
stderr 的文件描述符为 2,程序会向 stderr 流中写入错误信息。
错误输出重定向符("2>")
# 将命令的错误输出重定向到文件error.txt中
# 如果文件不存在,则创建文件;如果文件存在,则覆盖文件内容
ls not-exist-directory/ 2> error.txt
# 输出error.txt文件内容
cat error.txt
# 输出:
ls: cannot access 'not-exist-directory/': No such file or directory
合并标准输出和错误输出(">&")
1>&2 正确返回值传递给 2 输出通道 &2 表示 2 输出通道
2>&1 错误返回值传递给 1 输出通道, &1 表示 1 输出通道
注意不能有空格
创建文件结构
mkdir exist-directory
touch exist-directory/exist-file.txt
# 将命令的错误输出合并到标准输出通道
# 并写入文件out.txt中
ls not-exist-directory/ exist-directory/ > out.txt 2>&1
# 输出out.txt文件内容
cat out.txt
# 输出:
ls: cannot access 'not-exist-directory/': No such file or directory
exist-directory/:
exist-file.txt
# 先理解
ls not-exist-directory/ exist-directory/ > out.txt
# 等于
ls not-exist-directory/ exist-directory/ 1> out.txt
# 这是将标准输出重定向到文件out.txt中,而错误输出还是输出到终端
# 同理
ls not-exist-directory/ exist-directory/ 2> out.txt
# 这是将错误输出重定向到文件out.txt中,而标准输出还是输出到终端
# 将命令的标准输出合并到错误输出
# 并将合并后的错误输出写入文件out.txt中
ls not-exist-directory/ exist-directory/ 2> out.txt 1>&2
# 输出out.txt文件内容
cat out.txt
# 输出:
ls: cannot access 'not-exist-directory/': No such file or directory
exist-directory/:
exist-file.txt
合并输出到文件("&>")
# 将命令的标准输出和错误输出合并到文件out.txt中。
# 是上面两种方式的简写
ls not-exist-directory/ exist-directory/ &> out.txt
# 输出out.txt文件内容
cat out.txt
# 输出:
ls: cannot access 'not-exist-directory/': No such file or directory
exist-directory/:
exist-file.txt
因此,常见的命令如:
xxx &> /dev/null
xxx > /dev/null 2>&1
意思是将xxx程序的标准输出和错误输出都重定向到/dev/null文件中,即丢弃输出。
Very helpful :D, arch tutorial next?