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 2022-03-21 10:58  开心种树  阅读(384)  评论(0编辑  收藏  举报