代码块 重定向到 文件中

第一种方法:这里用的是:追加( >> ),也可以用:重写( > )。手动键盘输入( hello\ntest ),然后 Ctrl + c 结束输入。

  1. 如果 file.sh 存在,将下面两行内容( hello\ntest )追加到原有内容的后面。 
  2. 如果 file.sh 不存在,则创建 file.sh 后再写入下面两行内容( hello\ntest )。
[root@localhost home]# cat >> file1.sh
hello
test
^C                                        # Ctrl + c
[root@localhost home]# 
[root@localhost home]# cat file1.sh
hello
test
[root@localhost home]#

也可以用 Ctrl + D 来结束输入。 

[root@localhost home]# cat >> file1.sh
hello
test
Ctrl + D                                  # 按 Ctrl + D,不是输入 “Ctrl + D” 这个字符串,光标是在新的一行,下次输入从这里开始
[root@localhost home]# 
[root@localhost home]# cat file1.sh
hello
test
[root@localhost home]#
[root@localhost home]# cat >> file1.sh
hello
test(Ctrl + D)                            # 如果是在 test 后面按的话,光标是在 test 后面,而不是在新的一行,下次输入是从这里开始
[root@localhost home]#

第二种方法:相较上面多一个 分界符( EOF )。手动键盘输入( hello\ntest ),然后 EOF 结束输入。(最好用 EOF,当然也可以用其它的字符,前后保持对应一致即可。)1,2 点同上,不再列出。

[root@localhost home]# cat >> file2.sh  << EOF    # 分界符标志起始
> hello
> test
> EOF                                             # 分界符标志结束,前后对应一致
[root@localhost home]#
[root@localhost home]# cat file2.sh
hello
test
[root@localhost home]#

这两种方法推荐用第二种:因为我们输入的内容换行后,就不能再去修改上一行了。

比如:上面有两行内容 ( hello\ntest ),到第二行 test 时,我才发现第一行输错了,比如,原本应该是 "hello world",但是发现少了 world,这时是不能回到第一行修改的,我想结束掉(我有强迫症,看着不舒服,想重新输入),就用 Ctrl + c 结束输入(一般都是 Ctrl + c 结束不想执行的命令,不清楚还有没有其它方式)。

但是如果是第一种方法的话,这时就保存了,我们要通过其它方法去修改它。如果 filexx.sh 文件本身不存在的话,就会被创建。

但是如果是第二种方法的话,这就不会保存。如果文件 filexx.sh 本身不存在的话,也不会被创建。

另外的小结,结合上面的方法,这里简单介绍下,在文件中通过上面的语句去创建新文件和内容。

  1. 首先通过 vim 进行文件内容的编辑,vim file3.sh,写入下面的 内容:这里是,当 file3.sh 执行的时候,创建一个新文件 example.sh 并写入4行内容( hello world\n# export path\n\nabc 123) ,这里用的是 分界符 的方式,但是在文件中写的时候,就不用写上面的 '> ' 这个字符串(上面的 '> ' 是系统自动输出的),直接写内容。 
cat >> example.sh << EOF
hello world
# export path

abc 123
EOF

猜你喜欢

转载自blog.csdn.net/tk1023/article/details/108859175