1.创建文件读写描述符: <>
#!/bin/bash
exec 3<> fileContent.sh
#从fileContent.sh文件里面读取内容
read line <&3
echo "Read:$line"
#写入内容
echo "I have a Dream" >&3
- 当文件指针读完以后,指针在文件的最后一行。写的时候,是从指针所在的位置开始写的。
2.关闭文件读写
关闭文件描述符 'exec 3>&-'
#!/bin/bash
#自定义输出描述符
exec 3> fileContent.sh
echo "我是jack" >&3
#关闭文件描述符
exec 3>&-
#再次写入文件
echo "但是我喜欢装逼" >&3 // 会写入失败
执行脚本
weixiao$: ./fileA.sh
- 可以继续执行 exec 3> fileContent.sh 重新打开文件,来继续读写。
3.阻止命令输出
在终端使用
weixiao$: ls -l >/dev/null
或者
weixiao$: cat /dev/null > fileA.sh
4.创建临时文件
1.创建本地临时文件 mktemp
在终端使用
weixiao$: mktemp fileA.XXXXXX
weixiao$: mktemp fileA.sh
2.在shell脚本中创建临时文件
#!/bin/bash
#创建临时文件
tempfile=$(mktemp testfile.XXXXXX)
#重定向临时文件
exec 3> $tempfile
echo "我是jack" >&3
#关闭文件
exec 3>&-
#打印文件内容
cat $tempfile
#删除文件
rm -f $tempfile 2> /dev/null
- 使用rm -f命令 删除文件
3.在temp目录下创建临时文件:使用-t
在终端:
weixiao$: mktemp -t testFile.XXXXXX
在shell脚本中:
tempfile=$(mktemp -t testfile.XXXXXX)
4.创建临时目录: 使用-d
#!/bin/bash
temp=$(mktemp -d dir.XXXXXX) //创建临时目录
cd $temp //cd到目录下
file1=$(mktemp file.XXXXXX) // 创建临时文件
exec 3> $file1
echo "hello" >&3
5. 记录消息
既打印消息,又将消息发送到日志文件, 可以重定向2次, 也可以直接使用tee命令。
1.覆盖
weixiao$: data | tee fileContent.sh // 会在终端和文件中输出时间。
- 追加 ,加一个参数-a
weixiao$: data | tee -a fileContent.sh
3.在shell脚本中:
#!/bin/bash
#定义文件名称
tempfile="testfile"
echo "我要输出到控制台和文件" | tee $tempfile
echo "我要追加内容" | tee -a $tempfile
6.将表格文件导入到sql中。
#!/bin/bash
#定义数据库文件(.sql)文件
outfile="test.sql"
#定义域分隔符->分割字符串
IFS=','
while read name sex age
do
cat >> $outfile << EOF
INSERT INTO t test(name,sex,age) VALUES('$name','$sex','$age')
EOF
done < ${1}
执行脚本:传入表格文件
weixiao$: ./fileA.sh test.cvs
- done < ${1} 输入重定向:通过参数test.cvs 输入表格文件
- cat >> test.sql 输出重定向: cat是等待输入,然后输出重定向到test.sql
- 输入重定向 (cat >> test.sql)<< sql语句。