如何将部分bash脚本导出为外部文件

Ada*_*ski 2 bash

我编写了一个脚本来管理创建lxc虚拟容器的创建.它由在主机上执行的部分和由容器(虚拟客户)执行的部分组成.如果我可以在文件中编写这两个脚本,并在需要时从中提取第二个脚本(并随后在容器上运行),那将更加优雅.

我依稀记得,在bash中有一种方法可以做到这一点,但我不知道如何找到这个功能的名称以及如何使用它.

我需要这样的东西:

#/bin/bash

# here are commands that are to
# be executed by the host

<declare start of the code chunk that will be exported to file>

    # here go commands that 
    # need to be invoked by the guest

<end of code chunk. Paste the above code into the /var/lib/lxc/<mycontainer>/rootfs/tmp/second-stage.sh>

sudo lxc-attach -n <container name> /tmp/second-stage.sh
Run Code Online (Sandbox Code Playgroud)

Adr*_*rth 5

您可以使用此文档将多行文本重定向到相关文件.由于您的文档正文包含代码,因此您需要通过引用heredoc分隔符字符串('EOT')来禁用参数替换以避免有趣的副作用:

[...]
cat >/var/lib/lxc/<mycontainer>/rootfs/tmp/second-stage.sh <<'EOT'
# your text/code goes here
EOT
[...]
Run Code Online (Sandbox Code Playgroud)

  • 这里的文档文本成为命令的标准输入,但我不认为有一个内置命令会将其标准输入复制到命名文件.命令很便宜,而`cat`是一个便宜的命令.在担心它之前证明它是一个瓶颈(它不会是).(优化的第一定律:不要这样做.优化的第二定律 - 仅限专家:现在不要这样做.) (2认同)