如何在bash中定义动态变量?
我想要一个可以在每次引用时动态运行的 shell 变量,例如,我想要一个变量 $countPwd ,它可以返回当前目录中文件/目录的计数,它可以定义为:
countPwd=`ls | wc -l`
如果我执行 echo $countPwd ,它只会在定义变量时显示该值,但当我更改当前目录时它不会自动更新。那么我如何在 bash 中定义这样一个变量,使其值可以动态更新/计算呢?
更新: $PWD 是实时评估变量的完美示例。您不需要使用 $() 或反引号 `` 来评估它。 bash 中是如何定义的?
I would like to have a shell variable that could be dynamically run every time it is refered, for example, i would like to have a variable $countPwd which could return the count of files/dirs in the current directory, it could be defined as:
countPwd=`ls | wc -l`
and if I do echo $countPwd
it would only show the value when I define the variable, but it won't update automatically when I change my current directory. So how do I define such a variable in bash that the value of it get updated/calculated on the fly?
Update:
The $PWD is a perfect example of a variable get evaluated in the real time. You don't need to use $() or backticks `` to evaluate it. How is it defined in bash?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
创建一个函数:
然后像任何其他命令一样调用该函数:
Make a function:
Then call the function like any other command:
另一种选择:将命令存储在变量中,并在需要时对其进行评估:
Another option: store the command in a variable, and evaluate it when required:
您需要编写一些 C 代码:编写 bash 的 可加载内置,用于定义具有动态值的变量,例如
$SECONDS
或$RANDOM
($PWD
只是由cd
设置)。更多详细信息请参阅我的答案此处(此问题的重复项)。
You'll need to write some C code: write a bash's loadable buitins to do the heavy lifting in defining variables with dynamic values like
$SECONDS
or$RANDOM
($PWD
is just set bycd
).More details in my answer here (a duplicate of this question).