简体   繁体   English

bash中的\\ $$有什么用?

[英]What's the use of \$$ in bash?

I found this as a suggestion of how to store the output of "eval" into a variable called line. 我发现这是关于如何将“ eval”的输出存储到名为line的变量中的建议。 So, what's the use of \\$$ ? 那么, \\$$的用途是什么?

command = "some command"
line = $(eval \$$command)

The \\$ prevents the shell from trying to treat the $ as the beginning of a parameter expansion. \\$防止外壳程序尝试将$视为参数扩展的开始。 However, the code as a whole doesn't do anything useful. 但是,整个代码没有任何用处。 After fixing the whitespace issues and adding a real command to the example, your code looks like 解决空白问题并向示例添加真实命令后,您的代码如下所示

command="ls -l"
line=$(eval \$$command)

command is simply a string ls -l . command只是一个字符串ls -l To evaluate the next line, the shell first evaluates the command substitution. 为了评估下一行,shell首先评估命令替换。 The first step is to expand the parameter command , yielding line=$(eval \\$ls -l) . 第一步是扩展参数command ,产生line=$(eval \\$ls -l) Quote removal gets rid of the backslash, so eval receives the arguments $ls and -l . 删除引号可以消除反斜杠,因此eval接收参数$ls-l Since ls presumably is not a variable, $ls is expanded to the empty string, and eval is left simply with -l to execute. 由于ls可能不是变量,因此$ls会扩展为空字符串,而eval只需使用-l即可执行。 There being no such command, you get an error. 没有这样的命令,您会得到一个错误。

You might think, then, that the correct form is simply 那么,您可能会认为正确的形式就是

line=$(eval $command)

or slightly better 或稍微好一点

line=$(eval "$command")

That will work for simple cases, but not in general. 这将适用于简单的情况,但通常不会。 This has been hashed over many times in many questions; 这在很多问题中被散列了很多遍。 see Bash FAQ 50, "I'm trying to put a command in a variable, but the complex cases always fail!" 请参阅Bash常见问题解答50, “我试图将命令放入变量中,但是复杂的情况总是会失败!” for the details. 有关详细信息。


To answer the literal question, though, \\$$ is useful for outputing the string $$ , instead of expanding it to the current process ID: 不过,要回答字面问题, \\$$对于输出字符串$$很有用,而不是将其扩展为当前进程ID:

# The exact output will vary
$ echo $$
86542

# Literal quotes
$ echo \$\$
$$

# Escaping either quote is sufficient
$ echo \$$ $\$
$$ $$

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

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