【问题标题】:use cat << EOT >> to insert actual strings and escape logic使用 cat << EOT >> 插入实际字符串和转义逻辑
【发布时间】:2020-05-03 13:28:57
【问题描述】:

我正在编写一个脚本来在 AWS 临时卷上自动创建 SWAP。该过程的一部分需要脚本“感知”哪个 nvme 应用交换,因为 AWS Linux 可以在停止/启动时重新排序 nvme 名称。

我正在使用 Terraform 运行一个“启动”脚本,该脚本对实例执行大量操作。其中之一是将脚本插入/opt/scripts,然后添加将运行此自动交换脚本@reboot 的crontab。

但是,当我运行 Terraform 启动脚本时,它会将我的 cat EOT 替换为我的逻辑结果,而不是 /opt/scripts/swap.sh 中我想要的实际脚本。

这是我的 EOT 启动脚本的一部分:

# Create auto-swap script
mkdir /opt/scripts
cat <<EOT >> /opt/scripts/swap.sh
#!/bin/bash
exec 3>&1 4>&2
trap 'exec 2>&4 1>&3' 0 1 2 3
exec 1>/opt/scripts/swap.log 2>&1
# Create SWAP partition
sudo mkswap $(lsblk | grep  "279.4G" | cut -d " " -f1 | perl -ne 'print "/dev/$_"')
sudo swapon $(lsblk | grep  "279.4G" | cut -d " " -f1 | perl -ne 'print "/dev/$_"')
swapon -s
EOT

这是我运行 Terraform 后 /opt/scripts/swap.sh 内部的内容:

#!/bin/bash
exec 3>&1 4>&2
trap 'exec 2>&4 1>&3' 0 1 2 3
exec 1>/opt/scripts/swap.log 2>&1
# Create SWAP partition
sudo mkswap /dev/nvme1n1
sudo swapon /dev/nvme1n1
swapon -s

我需要 cat EOT 将我在脚本中显示的内容完全创建到 /opt/scripts/swap.sh 中,而不是它自己发现的 /dev/nvme1n1 中。我该怎么做?

/opt/scripts/swap.sh 的所需内容:

#!/bin/bash
exec 3>&1 4>&2
trap 'exec 2>&4 1>&3' 0 1 2 3
exec 1>/opt/scripts/swap.log 2>&1
# Create SWAP partition
sudo mkswap $(lsblk | grep  "279.4G" | cut -d " " -f1 | perl -ne 'print "/dev/$_"')
sudo swapon $(lsblk | grep  "279.4G" | cut -d " " -f1 | perl -ne 'print "/dev/$_"')
swapon -s

【问题讨论】:

    标签: linux bash amazon-web-services shell amazon-ec2


    【解决方案1】:

    你需要引用分隔符;现在,此处的文档被视为双引号字符串,因此命令替换被评估立即。

    # Create auto-swap script
    mkdir /opt/scripts
    cat <<'EOT' >> /opt/scripts/swap.sh
    #!/bin/bash
    exec 3>&1 4>&2
    trap 'exec 2>&4 1>&3' 0 1 2 3
    exec 1>/opt/scripts/swap.log 2>&1
    # Create SWAP partition
    sudo mkswap $(lsblk | grep  "279.4G" | cut -d " " -f1 | perl -ne 'print "/dev/$_"')
    sudo swapon $(lsblk | grep  "279.4G" | cut -d " " -f1 | perl -ne 'print "/dev/$_"')
    swapon -s
    EOT

    【讨论】:

    • 或者像这样cat &lt;&lt; \EOT &gt;&gt; /opt/scripts/swap.sh
    猜你喜欢
    • 2018-05-12
    • 2021-07-23
    • 2020-01-14
    • 2012-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-29
    相关资源
    最近更新 更多