[Shell详解-10]:文件重定向

Shell语法详解目录

文章目录

每个进程默认打开3个文件描述符:

  1. stdin标准输入,从命令行读取数据,文件描述符为0;
  2. stdout标准输出,向命令行输出数据,文件描述符为1;
  3. stderr标准错误输出,向命令行输出数据,文件描述符为2;

可以用文件重定向将这三个文件重定向到其他文件中。

重定向命令

命令 说明
command > file stdout重定向到file
command < file stdin重定向到file
command >> file stdout以追加方式重定向到file
command n> file 将文件描述符n重定向到file
command n>> file 将文件描述符n以追加方式重定向到file

示例1

echo -e "Hello \c" > output.txt  # 将字符出重定向输出到output.txt中
echo "World" >> output.txt  # 将字符串追加到output.txt中

read str < output.txt  # 从output.txt中读取字符串

echo $str  # 输出结果:Hello World

示例2
创建test.sh脚本

#! /bin/bash

read a
read b

echo $(expr "$a" + "$b")

创建input.txt,里面的内容为:

3
4

执行命令

bash test.sh < input.txt > output.txt
cat output.txt

输出 7

示例3


echo "$(< input.txt)" # 输出input.txt中的内容

ls > a.txt # 将当前目录下的文件列表写入a.txt中

猜你喜欢

转载自blog.csdn.net/weixin_52341477/article/details/127613715