在 bash 中 \$$ 有什么用? [英] What's the use of \$$ in bash?

查看:76
本文介绍了在 bash 中 \$$ 有什么用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现这是关于如何将eval"的输出存储到名为 line 的变量中的建议.那么,\$$ 有什么用?

I found this as a suggestion of how to store the output of "eval" into a variable called line. So, what's the use of \$$?

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

推荐答案

\$ 阻止 shell 尝试将 $ 视为参数扩展的开始.但是,整个代码没有做任何有用的事情.修复空白问题并向示例添加实际命令后,您的代码看起来像

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 只是一个字符串 ls -l.为了评估下一行,shell 首先评估命令替换.第一步是扩展参数command,产生line=$(eval \$ls -l).引用删除去掉了反斜杠,所以 eval 接收参数 $ls-l.由于 ls 大概不是一个变量,$ls 被扩展为空字符串,而 eval 只剩下 -l 执行.没有这样的命令,你会得到一个错误.

command is simply a string ls -l. To evaluate the next line, the shell first evaluates the command substitution. The first step is to expand the parameter command, yielding line=$(eval \$ls -l). Quote removal gets rid of the backslash, so eval receives the arguments $ls and -l. Since ls presumably is not a variable, $ls is expanded to the empty string, and eval is left simply with -l to execute. There being no such command, you get an error.

可能认为,那么,正确的形式就是

You might think, then, that the correct form is simply

line=$(eval $command)

或者稍微好一点

line=$(eval "$command")

这适用于简单的情况,但不适用于一般情况.这已在许多问题中多次散列;请参阅 Bash 常见问题 50,"我试图将命令放入变量中,但复杂的情况总是失败!" 了解详情.

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!" for the details.

不过,要回答字面问题,\$$ 可用于输出字符串 $$,而不是将其扩展为当前进程 ID:

To answer the literal question, though, \$$ is useful for outputing the string $$, instead of expanding it to the current process ID:

# The exact output will vary
$ echo $$
86542

# Literal quotes
$ echo \$\$
$$

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

这篇关于在 bash 中 \$$ 有什么用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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