0

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?

1
  • 1
    Write a cover function for cd that sets the variable when you have changed directory. Or create a script or function (perhaps fc for 'file count') and simply use that (less typing). Commented May 3, 2011 at 19:38

3 Answers 3

6

Make a function:

countPwd() {
    ls | wc -l
}

Then call the function like any other command:

echo "There are $(countPwd) files in the current directory."
Sign up to request clarification or add additional context in comments.

3 Comments

but that's not a variable, so I still can't do echo $countPwd. In another word, I would like to have a variable similar to the $PWD in bash. The $PWD is a perfect example of a variable get evaluated in the real time. How is it defined?
PWD is a "sell variable"; somehow a «builtin». Also it is not evaluated in real time, it is set by the cd command (as per what bash's man page says). IMHO the workaround proposed using a bash function is quite good (+1)
@hmontoliu Thanks. I guess your explaination about cd command solve the mystery, then I guess John's answer is my solution.
0

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

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

2 Comments

-1 Really terrible idea. I know you can't go wrong with a number, but if someone changes the value of countPwd you're SOL.
@l0b0 You can make countPwd readonly to alleviate that concern.
0

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

1 Comment

If there is a good duplicate, then this question should be closed as duplicate. But at least you spent the time to really answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.