(1) vi bundle.sh
#! /bin/bash #bundle :group files into distribution package echo "# To unbundle, bash this file" for i do echo "echo $i 1>&2" echo "cat >$i <<'End of $i'" cat $i echo "End of $i" done
(2)
hello1
hello2
cat h2.txt hello3(3) 执行sh boudle.sh h1.txt h2.txt >bakfiles
(4)
rm h1.txt h2.txt
(5) 执行bash bakfiles可恢复h1.txt,h2.txt
【解析】
(1)为什么执行bash bakfiles可恢复h1.txt,h2.txt?
先来看一下bakfiles的内容,执行cat bakfiles
# To unbundle, bash this file
echo h1.txt 1>&2
cat >h1.txt <<'End of h1.txt'
hello1
hello2
End of h1.txt
echo h2.txt 1>&2
cat >h2.txt <<'End of h2.txt'
hello3
End of h2.txt
原来在执行sh boudle.sh h1.txt h2.txt >bakfiles后,bakfiles中生成了2条文件重定向语句:
cat >h1.txt <<'End of h1.txt'
cat >h2.txt <<'End of h2.txt'
再用bash解析bakfiles也就达到了恢复文件的目的。
(2) 1>&2的涵义
0:标准输入
1:标准输出
2:标准错误
>&:可复制的文件描述符
1>&2即是将标准输出重定向为标准错误。
本文解释了如何使用bash脚本将多个文件批量打包并恢复,通过解析脚本执行过程和1>&2重定向原理,实现文件的批量备份与还原。
932

被折叠的 条评论
为什么被折叠?



