Bash尝试在Heredoc中执行命令 [英] Bash tries to execute commands in heredoc

查看:64
本文介绍了Bash尝试在Heredoc中执行命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个简单的bash脚本,该脚本将多行输出打印到另一个文件.我正在通过heredoc格式进行操作:

I am trying to write a simple bash script that will print a multiline output to another file. I am doing it through heredoc format:

#!/bin/sh

echo "Hello!"
cat <<EOF > ~/Desktop/what.txt
a=`echo $1 | awk -F. '{print $NF}'`
b=`echo $2 | tr '[:upper:]' '[:lower:]'`
EOF

我希望在桌面上看到包含以下内容的文件:

I was expecting to see a file in my desktop with these contents:

a=`echo $1 | awk -F. '{print $NF}'`
b=`echo $2 | tr '[:upper:]' '[:lower:]'`

但是,相反,我将这些内容视为我的what.txt文件的内容:

But instead, I am seeing these as the contents of my what.txt file:

a=
b=

以某种方式,即使它是heredoc的一部分,bash仍试图逐行执行它.我该如何防止这种情况,并将内容按原样打印到文件中?

Somehow, even though it is part of a heredoc, bash is trying to execute it line by line. How do I prevent this, and print the contents to the file as it is?

推荐答案

引用EOF,以便bash从字面上接受输入:

Quote EOF so that bash takes inputs literally:

cat <<'EOF' > what.txt
a=`echo $1 | awk -F. '{print $NF}'`
b=`echo $2 | tr '[:upper:]' '[:lower:]'`
EOF

也开始使用$()代替旧的和有问题的``.c5>来代替命令.

Also start using $() for command substitution instead of old and problematic ``.

这篇关于Bash尝试在Heredoc中执行命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆