variable=$(...) 是否将命令或命令的结果存储在 POSIX sh 中 [英] Does variable=$(...) store the command or the result of the command in POSIX sh

查看:48
本文介绍了variable=$(...) 是否将命令或命令的结果存储在 POSIX sh 中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道:当我例如打电话

I was wondering: When I e.g. call

list=$(ps -ax)

是 ps -ax 执行一次,我可以多次读取该值还是每次调用 $list 时执行的命令

is ps -ax executed once and I can read the value multiple times or is the command executed every time I call $list

推荐答案

POSIX sh 保证命令不会被重新执行,见下文.

POSIX sh guarantees that the command will not be re-executed, see below.

在通过经验测试得出有关 POSIX sh 的结论时要小心.例如,如果您计时 sleep 60 |真的,你会发现 bash、ksh、zsh 和 dash 都需要 60 秒.但是,POSIX sh 仍然允许它立即完成.

Be careful about concluding things about POSIX sh through empirical tests. For example, if you time sleep 60 | true, you'd find that bash, ksh, zsh and dash all take 60 seconds. However, POSIX sh still allows it to finish immediately.

$() 的规范:

shell 应通过在子 shell 环境中执行命令来扩展命令替换(请参阅 Shell 执行环境)并将命令替换(命令文本加上封闭的$()"或反引号)替换为标准输出的命令.

The shell shall expand the command substitution by executing command in a subshell environment (see Shell Execution Environment) and replacing the command substitution (the text of command plus the enclosing "$()" or backquotes) with the standard output of the command.

应用时:

当需要执行给定的简单命令时[...],以下扩展、赋值和重定向都应从命令文本的开头到结尾执行:

When a given simple command is required to be executed [...] the following expansions, assignments, and redirections shall all be performed from the beginning of the command text to the end:

[...]

  1. 在赋值之前,每个变量赋值都应针对波浪号扩展、参数扩展、命令替换、算术扩展和引号删除进行扩展.

[...]

变量赋值应如下执行:

如果没有命令名结果,变量赋值将影响当前的执行环境.

If no command name results, variable assignments shall affect the current execution environment.

由于 $() 被替换为命令的文本,并且这发生在变量被赋值之前,所以保证不会在符合 POSIX sh 的实现中重新执行该命令.

Since $() is replaced with the text of the command, and this happens before the variable is assigned, the command is guaranteed not to be re-executed in a conforming POSIX sh implementation.

这篇关于variable=$(...) 是否将命令或命令的结果存储在 POSIX sh 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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