开发者

How to define dynamic variable in bash? [duplicate]

开发者 https://www.devze.com 2023-03-03 03:07 出处:网络
This question already 开发者_StackOverflow中文版has answers here: How to create a bash variable like $RANDOM
This question already 开发者_StackOverflow中文版has answers here: How to create a bash variable like $RANDOM (3 answers) Closed 5 years ago.

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?


Make a function:

countPwd() {
    ls | wc -l
}

Then call the function like any other command:

echo "There are $(countPwd) files in the current directory."


Another option: store the command in a variable, and evaluate it when required:

countPwd='ls | wc -l'
echo $(eval "$countPwd")


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 by cd).

More details in my answer here (a duplicate of this question).

0

精彩评论

暂无评论...
验证码 换一张
取 消