简体   繁体   English

内联bash脚本变量

[英]Inline bash script variables

Admittedly, I'm a bash neophyte. 不可否认,我是一名新手。 I always want to reach for Python for my shell scripting purposes. 我总是希望为我的shell脚本目的而使用Python。 However, I'm trying to push myself to learn some bash. 但是,我正试图让自己学习一些bash。 I'm curious why the following code doesn't work. 我很好奇为什么以下代码不起作用。

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

It doesn't work because variable expansion in the double-quoted string happens before the command is called. 它不起作用,因为双引号字符串中的变量扩展在调用命令之前发生。 That is, if I type: 也就是说,如果我输入:

echo "$HOME"

The shell transforms this into: shell将其转换为:

echo "/home/lars"

Before actually calling the echo command. 在实际调用echo命令之前。 Similarly, if you type: 同样,如果您输入:

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

This gets transformed into: 这变成了:

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

Before calling a the sh command. 在调用sh命令之前。 You can use single quotes to inhibit variable expansion, for example: 您可以使用单引号来禁止变量扩展,例如:

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

You can also escape the $ with a backslash: 你也可以用反斜杠来逃避$

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM