BASH 脚本,无需替换即可将变量传递到新脚本中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7549404/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 00:52:43  来源:igfitidea点击:

BASH script to pass variables without substitution into new script

bashsubstitution

提问by interoperate

As part of a system build script I have a script that creates various files and configurations.

作为系统构建脚本的一部分,我有一个创建各种文件和配置的脚本。

However one part of the build script creates a new script that contains variables that I don't want resolved when the build script runs. Code snippet example

但是,构建脚本的一部分创建了一个新脚本,其中包含我不希望在构建脚本运行时解析的变量。代码片段示例

cat - > /etc/profile.d/mymotd.sh <<EOF
hostname=`uname -n`
echo -e "Hostname is $hostname"
EOF

I have tried all sorts of combinations of ' and " and ( and [ but I cannot get the script to send the content without substituting the values and placing the substitutes in the new script rather than the original text.

我已经尝试了 ' 和 " 和 ( 和 [ 的各种组合,但是如果不替换值并将替换值放置在新脚本而不是原始文本中,我就无法让脚本发送内容。

Ideas?

想法?

回答by Jonathan Callen

The easiest method, assuming you don't want anything to be substituted in the here doc, is to put the EOF marker in quotes, like this:

最简单的方法,假设您不想在此处的文档中替换任何内容,则将 EOF 标记放在引号中,如下所示:

cat - > /etc/profile.d/mymotd.sh <<'EOF'
hostname=`uname -n`
echo -e "Hostname is $hostname"
EOF

回答by ott--

Easiest is to escape the $

最简单的就是逃避$

echo -e "Hostname is \$hostname"

echo -e "主机名是 \$hostname"