内联 bash 脚本变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9961032/
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 01:55:51  来源:igfitidea点击:

Inline bash script variables

bash

提问by Daniel

Admittedly, I'm a bash neophyte. I always want to reach for Python for my shell scripting purposes. However, I'm trying to push myself to learn some bash. I'm curious why the following code doesn't work.

不可否认,我是一个 bash 新手。我总是想为我的 shell 脚本目的使用 Python。但是,我正在努力促使自己学习一些 bash。我很好奇为什么下面的代码不起作用。

sh -c "F=\"123\"; echo $F"

回答by larsks

It doesn't work because variable expansion in the double-quoted string happens beforethe command is called. That is, if I type:

它不起作用,因为双引号字符串中的变量扩展发生调用命令之前。也就是说,如果我输入:

echo "$HOME"

The shell transforms this into:

外壳将其转换为:

echo "/home/lars"

Before actually calling the echo command. Similarly, if you type:

在实际调用 echo 命令之前。同样,如果您键入:

sh -c "F=\"123\"; echo $F"

This gets transformed into:

这被转化为:

sh -c "F=\"123\"; echo"

Before calling a the shcommand. You can use single quotes to inhibit variable expansion, for example:

在调用sh命令之前。您可以使用单引号来禁止变量扩展,例如:

sh -c 'F="123"; echo $F'

You can also escape the $with a backslash:

你也可以$用反斜杠转义:

sh -c "F=\"123\"; echo $F"