好好爱自己!

linux bash关闭标准输出1(exec 1<&-)后重新打开

linux bash shell的再次学习。

文件描述符:

stdin,stdout 和 stderr 的文件描述符分别是 0,1 和 2(一个文件描述符说白了就是文件系统为了跟踪这个打开的文件而分配给它的一个数字)

1 .避免管道产生的子shell

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#!/bin/bash
 
E_WRONG_ARGS=71
if [ -z "$1" ]
then
    echo "Usage: $0 input-file"
    exit $E_WRONG_ARGS
fi
 
Lines=0
 
cat "$1" | while read line; # 管道会产生子 shell
do {
    echo $line
    (( Lines++ )); #  增加这个变量的值
    # 但是外部循环却不能访问
}
done
 
echo "Number of lines read = $Lines" # 0
# 错误!
echo "------------------------"
exec 3<> "$1"
while read line <&3
do {
    echo "$line"
    (( Lines++ )); #  增加这个变量的值
    # 现在外部循环就可以访问了
    #  没有子shell, 现在就没问题了
}
done
exec 3>&-
echo "Number of lines read = $Lines"
exit 0
                                                                            

  

 

2.绑定屏幕的便准输出到 out这个文件,即将所有的标准输出都输出到out这个文件当中。

 

--------------------------------------------------

参考:https://www.cnblogs.com/sparkdev/p/10247187.html

这样子来读入文件fly的内容

 清空文件

 

----------------------------------------------------------------------------

Reopen STDOUT and STDERR after closing them?

I am running this on an Ubuntu machine, so I am not sure if it'll work for you, but this is what I did:

$ exec 1>&0
$ exec 2>&0

Suddenly, I had STDOUT and STDERR reconnected. Magic!

Explanation: Running the following commands, we get the following output:

$ ls -l /dev/stdout
lrwxrwxrwx 1 root root 15 Jun 11 23:39 /dev/stdout -> /proc/self/fd/1

$ ls -l /proc/self/fd/1
lrwx------ 1 jay jay 64 Jun 22 01:34 /proc/self/fd/1 -> /dev/pts/10

$ ls -l /proc/self/fd/
total 0
lrwx------ 1 jay jay 64 Jun 22 01:35 0 -> /dev/pts/10
lrwx------ 1 jay jay 64 Jun 22 01:35 1 -> /dev/pts/10
lrwx------ 1 jay jay 64 Jun 22 01:35 2 -> /dev/pts/10
lr-x------ 1 jay jay 64 Jun 22 01:35 3 -> /proc/12224/fd

Since all three fd's point to the same thing, we can return them back to normal just by pointing to /dev/pts/10 which the exec 1>&0 and exec 2>&0 do

posted @   立志做一个好的程序员  阅读(2629)  评论(0编辑  收藏  举报
编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· AI与.NET技术实操系列(六):基于图像分类模型对图像进行分类

不断学习创作,与自己快乐相处

点击右上角即可分享
微信分享提示