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).
精彩评论