bash手册 之重定向原理与实现

本文详细介绍了Shell脚本中标准输入输出的重定向方法,包括如何使用exec命令进行文件描述符的操作,以及通过eval命令来动态设置变量。通过实际示例展示了如何将输入重定向到文件以及如何通过eval重新提交shell。

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

http://www.gnu.org/software/bash/manual/bashref.html#Redirections

http://www.cnblogs.com/weidagang2046/p/io-redirection.html 原理与实现

http://blog.youkuaiyun.com/taiyang1987912/article/details/39401265

[root@server1 tmp]# cd /dev/fd
[root@server1 fd]# ll
总用量 0
lrwx------ 1 root root 64 6月 4 12:17 0 -> /dev/pts/0
lrwx------ 1 root root 64 6月 4 12:17 1 -> /dev/pts/0
lrwx------ 1 root root 64 6月 4 12:17 2 -> /dev/pts/0
lrwx------ 1 root root 64 6月 4 12:17 255 -> /dev/pts/0

 

#使用exec将stdin重定向到文件
#!/bin/bash

exec 8<&0           #FD 8是FD 0的副本,用于恢复标准输入
exec < file         #将标准输入重定向到file
read a              #读取file的第一行
read b              #读取file的第二行
echo "read has read $$"
echo "read has read $PPID"
sleep 100
echo "----------------"
echo $a             #标准输出
echo $b             #标准输出

该进程的文件描述符FD 变为如下

[root@server1 fd]# ll
总用量 0
lr-x------ 1 root root 64 6月 4 13:03 0 -> /root/file
lrwx------ 1 root root 64 6月 4 13:03 1 -> /dev/pts/0
lrwx------ 1 root root 64 6月 4 13:03 2 -> /dev/pts/0
lr-x------ 1 root root 64 6月 4 13:03 254 -> /root/a.sh
lrwx------ 1 root root 64 6月 4 13:03 255 -> /dev/pts/0
lrwx------ 1 root root 64 6月 4 13:03 8 -> /dev/pts/0

 

 

echo "close FD 8:"
exec 0<&8 8<&- #将FD 8复制到FD 0,恢复FD 0,并关闭FD 8,其他进程可以重复使用FD 8
echo -n "Enter Data:"
read c #read从标准输入读取数据
echo $c
echo $$
echo $PPID
sleep 100

 

[root@server1 4598]# ll fd
总用量 0
lrwx------ 1 root root 64 6月 4 13:11 0 -> /dev/pts/0
lrwx------ 1 root root 64 6月 4 13:11 1 -> /dev/pts/0
lrwx------ 1 root root 64 6月 4 13:11 2 -> /dev/pts/0
lr-x------ 1 root root 64 6月 4 13:11 254 -> /root/a.sh
lrwx------ 1 root root 64 6月 4 13:11 255 -> /dev/pts/0

 

 

#eval重新提交shell
#!/bin/bash

while read NAME VALUE     #第一列作为变量名,第二列作为变量值        //对应文件中的两列
do
eval "${NAME}=${VALUE}"   #第1轮变量替换,eval重新提交shell完成赋值操作     
done < evalsource         #输入重定向
echo "var1=$var1"         #变量赋值
echo "var2=$var2"

eval "${NAME}=${VALUE}" 为一段可执行的命令,而不是字符串

 

[root@server1 ~]# eval "cc=100"
[root@server1 ~]# echo $cc
100


[root@server1 ~]# echo "dd=100"
dd=100



 


[root@server1 ~]# x=100
[root@server1 ~]# ptrx=x
[root@server1 ~]# eval echo \$$ptrx
100
[root@server1 ~]# eval $ptrx=50
[root@server1 ~]# echo $x
50
[root@server1 ~]# echo $ptrx
x

 

转载于:https://www.cnblogs.com/zengkefu/p/5558539.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值