shell语法----文件重定向

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

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

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


重定向命令列表

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

输入和输出重定向

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

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

echo $str  # 输出结果:Hello World

同时重定向stdin和stdout
创建bash脚本:

#! /bin/bash

read a
read b

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

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

3
4

执行命令:

chmod +x test.sh  # 添加可执行权限
./test.sh < input.txt > output.txt  # 从input.txt中读取内容,将输出写入output.txt中
cat output.txt  # 查看output.txt中的内容
7
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值