How to create a bash variable like $RANDOM

后端 未结 3 1775
不思量自难忘°
不思量自难忘° 2021-01-16 23:46

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 , s

3条回答
  •  一生所求
    2021-01-16 23:50

    The special behavior of $RANDOM is a built-in feature of bash. There is no mechanism for defining your own special variables.

    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)
    

    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.

提交回复
热议问题