I want to retrieve the total number of files within a folder.

I would do this with ls | wc -l. My code is:

cd /home/user/myfolder
num=$("ls | wc -l")

But I understand this opens a new shell which doesn't know that the working directory was changed. How can I execute the ls | wc -l command within the same shell?


Your command doesn't work merely because you quoted it, actually the action of bash Command Substitution does take place in the current working directory. However, as you should avoid parsing the output of ls I recommend a different approach.

I like using find for things like that:

find . -maxdepth 1 -type f -printf . | wc -c

This prints a . (-printf .) for every file (-type f) in the current directory (. and -maxdepth 1), wc then just counts the bytes in the output.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.