如何创建像$ RANDOM这样的bash变量 [英] How to create a bash variable like $RANDOM
问题描述
我对某些事情很感兴趣:每次我echo $RANDOM
时,显示值都会有所不同.我猜想RANDOM是特殊的(当我阅读它时,它可能会调用一个函数,设置一个变量标志并返回RANDOM编号.).我想创建一个这样的变量,我该怎么做?每个答案都会有帮助.
I'm interest in some thing : every time I echo $RANDOM
, the show value difference . I guess the RANDOM is special (When I read it , it may call a function , set a variable flag and return the RANDOM number . ) . I want to create a variable like this , how I can do it ? Every answer will be helpful .
推荐答案
$RANDOM
的特殊行为是bash的内置功能.没有定义自己的特殊变量的机制.
The special behavior of $RANDOM
is a built-in feature of bash. There is no mechanism for defining your own special variables.
您可以编写一个函数,该函数在每次调用时打印一个不同的值,然后以$(func)
的形式调用它.例如:
You can write a function that prints a different value each time it's called, and then invoke it as $(func)
. For example:
now() {
date +%s
}
echo $(now)
或者您可以将$PROMPT_COMMAND
设置为更新指定变量的命令.它会在打印每个提示之前运行.
Or you can set $PROMPT_COMMAND
to a command that updates a specified variable. It runs just before printing each prompt.
i=0
PROMPT_COMMAND='((i++))'
这在脚本中不起作用(因为没有打印提示),并且无论您是否引用该变量,这都会造成开销.
This doesn't work in a script (since no prompt is printed), and it imposes an overhead whether you refer to the variable or not.
这篇关于如何创建像$ RANDOM这样的bash变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!