跟我一起写Shell脚本之十五---写文件

1、创建一个新文件并写入内容

我们写脚本如下:

#!/bin/bash

echo "Begin to write our own file"

if [ $# -lt 1 ]; then
        filename="myfile1"
else
        filename=$1
fi

cat>$filename<<EOF
first line
2nd line
hahahah
hohhoho
EOF

<<EOF 表示当遇到EOF时结束输入。

执行结果如下:

$ sh 030-file1.sh 
Begin to write our own file
$ ls
030-file1.sh  myfile1
$ cat myfile1 
first line
2nd line
hahahah
hohhoho

注意:这时候如果我们再次执行sh 030-file1.sh,myfile1的内容是不改变的。原因是脚本里我们用了cat>$filename<<EOF,每次写入都是覆盖写入。

           如果我们用cat>>$filename<<EOF结果会如何呢?

2、追加写入内容

我们修改脚本如下:

#!/bin/bash

echo "Begin to write our own file"

if [ $# -lt 1 ]; then
        filename="myfile1"
else
        filename=$1
fi

cat>>$filename<<EOF
first line
2nd line
hahahah
hohhoho
EOF

执行后的结果为:

$ sh 031-file2.sh 
Begin to write our own file
$ ls
030-file1.sh  031-file2.sh  myfile1
$ cat myfile1 
first line
2nd line
hahahah
hohhoho
first line
2nd line
hahahah
hohhoho

可见myfile1的内容是追加的方式。

 

3、其他

我们也可以用

echo "aaaa" > $filename
echo "bbbb" >> $filename

简单的将字符串写入文件或者追加到文件。

#!/bin/bash

echo "Begin to write our own file"

if [ $# -lt 1 ]; then
        filename="myfile1"
else
        filename=$1
fi

echo "aaaa" > $filename
echo "bbbb" >> $filename

执行结果:

$ sh 032-file3.sh myfile2.txt
Begin to write our own file
$ cat myfile2.txt 
aaaa
bbbb

4、综合例子

我们写一个综合以上所有的内容的例子:

#!/bin/bash

echo "Begin to write our own file"

if [ $# -lt 1 ]; then
        filename="myfile1"
else
        filename=$1
fi

echo "filename is ${filename}" > ${filename}

for file in $(ls)
do
cat>>$filename<<EOF
this file is $file
EOF

done

执行结果:

$ sh 033-file4.sh hahaha
Begin to write our own file
$ cat hahaha 
filename is hahaha
this file is 030-file1.sh
this file is 031-file2.sh
this file is 032-file3.sh
this file is 033-file4.sh
this file is hahaha
this file is myfile1
this file is myfile2.txt

===================================================================================

注意:本文为本人原创,版权所属为个人所有,欢迎转载,但是转载请注明出处。

===================================================================================

  • 3
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值