跟我一起写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

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

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

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

Guess you like

Origin blog.csdn.net/sjwangjinbao/article/details/116422855