shell——输入输出管道

1. 标准输出

ls -l > ./test
ls -l 1> ./test
ls -l >> ./test

2. 标准输入

read oneline
while [ "oneline" != "" ]
do
  read oneline
done 

read命令:读取一行

./test.sh < 1.txt

3. 标准错误

ls -l >./output 2>./err
ls -l >./output_and_err 2>&1

4. 管道

cat $1 | while read oneline
do
  read oneline
done 

ls -l | tee ls.txt

tee,复制标准输入内容到标准输出和指定的文件中,可以复制到多个文件,tee类似于管道,一个输入,一个标准输出和多个文件输出。

4.1 区分命令行参数 和 标准输入

rm只接受命令行,不接受标准输入

rm -i $(find ./ -name *)

5. 块重定向

{date; echo "aaa"; pwd;} > ./out

也可以将 命令块 交给子进程执行,

(date; echo "aaa"; pwd;) > ./out

对用户指定的文件,每行添加行号

count=0
filename=$(basename $file)
while read line
do
  count=$((count+1))
  echo $count:$line
# 指定标准输入为 $file
# 指定 while 块 标准输出为 $file.lined
done <$file>$filename.lined

5.1 Here Document

Here Document 使用IO重定向形式记录一段临时文本或交互命令,并把这些文本或命令依次传递给一个程序或命令,作为运行时的标准输入。
语法

command <<delimiter
document
document
...
delimiter

delimiter 是输入的开始和结束标识符, delimiter可以用任意字符,常用 EOF,但 delimiter 只能是一个词,中间不能有空格或Tab。

cat <<EOF
aaa
bbb
EOF

posted on   开心种树  阅读(399)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
< 2025年3月 >
23 24 25 26 27 28 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 1 2 3 4 5

统计

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