管道 重定向释义

(1)管道是为了解决进程间通信问题而存在,管道左边输出数据,右边接收数据

(2)linux一切皆文件的特性,默认的输入输出文件是/dev/std{in,out,err},对应的文件描述符为0 1 2,表现出的输入输出都在屏幕上!

  这是数据流向的默认目标文件,但可以改流向 这就是重定向

一、重定向 

①文件覆盖与追加

 单箭头<,>,2>表示覆盖,双箭头>>,2>>表示追加;

 2>&1, &>, &>>表示将stdout和stderr重定向到同一个文件。

②清空文件的集中方式

> ab.sh
echo '' > ab.sh
cat /dev/null > ab.sh

> ab.sh

set -C

 

echo管道重定向 管道 重定向_数组

 ②cat搭配>

 <<eof表示:后面的内容作为一个document输入给cat,并且以eof作结束标记。 此功能用here document简记,<<<则是here string。

root@xu:/home/xu# cat > test.txt <<eof
> hello
> shine eof 20034
> eof
root@xu:/home/xu# var=`cat test.txt`; echo $var
hello shine eof 20034
root@xu:/home/xu# cat test.txt
hello
shine eof 20034

 此外可以其它搭配: 

  cat << eof  直接在终端输入,只是输入结束后 输出在终端显示

  cat file.txt > test.txt <<eof  把file.txt和在终端输入的字符 一起写入test.txt

  ls ../ | head -5 >> test.txt 

③tee双重定向

 输出的不再是终端或某文件,而是终端和某文件

 命令:tee [-a] file  把流入终端的内容也流入到文件。 -a表示追加,以下会覆盖a.log中原有的内容。

 

echo管道重定向 管道 重定向_echo管道重定向_02

  cat a* | tee -a b.log | cat  效果一样

  cat <<eof | tee c.log

cat -表示stdin

 总结tee就是利用管道|,将std流中的某一段数据流保存记录下来!

二、数组

①两种声明方式

arr=(here shine 20034)  或arr[0]=here;arr[1]=shine;arr[2]=20034,  注意第一种用空格而非,逗号隔开

  

echo管道重定向 管道 重定向_输入输出_03

使用方式:单个索引${arr[0]},所有值${arr[*]}, 数组所有索引号${!arr[*]},数组长度/元素个数${#arr[*]}

1.1关联数组(字典)

 

echo管道重定向 管道 重定向_echo管道重定向_04

声明与使用:declare -A arr;  arr[key]=value

②数组元素的截取和替换

arr0=${arr[*]:3:2}  index和count

 arr1=${arr[*]/shine/office}  把数组中shine替换成office

③for循环遍历数组

 

echo管道重定向 管道 重定向_数组_05

遍历文件里的每一行

echo管道重定向 管道 重定向_重定向_06

echo管道重定向 管道 重定向_echo管道重定向_07

portmapper
portmapper
portmapper
portmapper
portmapper
portmapper
status
status
mountd
mountd
mountd
mountd
mountd
mountd
nfs
nfs
nfs_acl
nfs
nfs
nfs_acl
nlockmgr
nlockmgr
nlockmgr
nlockmgr
nlockmgr
nlockmgr

x.log

#!/bin/bash

declare -A arr  # 定义关联数组

for i in `cat x.log`
do
    let ++arr[$i]
done

for j in ${!arr[*]}
do
    printf "%-15s %s\n" $j is${arr[$j]}
done

 

2021-12-08 19:25:28