shell脚本将单行或者多行字符以覆盖或者追加的方式写入文本文件中
1.写入单行和多行
单行
$ echo "hello wrold" > 1.txt
$ cat 1.txt
hello wrold
- 或者不加引号
$ echo hello wrold > 1.txt
$ cat 1.txt
hello wrold
多行
- 文件到文件:
$ cat 1.txt > 2.txt
- 或者手动写入
$ cat > 2.txt << o
> hello
> wrold
> c
> python
> io
> o
$ cat 2.txt
hello
wrold
c
python
io
- 命令中
<< o
表示遇见o
就结束输入,可以是其他任意字符;但是必须是单独字符o
,假如是io
仍然不会停止;且中止字符本身o
不会被写入
$ cat 2.txt > 3.txt << c 只会是2.txt的内容写入到3.txt中
2.覆盖写入和追加
覆盖写入 >
$ cat 1.txt
hello wrold
$ echo "happy new year" > 1.txt
happy new year
$ cat 1.txt
happy new year
追加 >>
$ cat 1.txt
hello wrold
$ echo hello wrold >> 1.txt
$ cat 1.txt
hello wrold
hello wrold
3.标准输入输出用法
linux
文件描述符
- 0 标准输入 stdin
- 1 标准输出 stdout
- 2 标准错误 stderr
- /dev/null “黑洞”,信息去向
几种常见用法
- 标准输出重定向
./test.sh 1> 1.txt
//或者
./test.sh > 1.txt
不指明描述符默认为1
- 错误输出重定向
./test.sh 2> 1.txt
- 标准输出和标准错误分开
./test.sh 1> 1.txt 2>2.txt
- 标准输出和标准错误合并
./test.sh 3.txt 2>&1
//或者
./test.sh &> 3.txt