1

What I am trying to do is to count all the files in a directory using shell script.

For example, when execute the program,

./test.sh project

it should count all the files in the folder called "project".

But I am having trouble with the directory part.

What I have done so far is,

#!/bin/bash

directory=$1
count=ls $directory | wc -l
echo "$folder has $count files"

but it does not work... Can anyone blow up my confusion please?

Thanks!

2
  • Look up what $( ) (or backticks) do. Commented Mar 18, 2018 at 10:46
  • It's called command substitution. If you are using bash, you should also familiarize yourself with process substitution. Commented Mar 18, 2018 at 11:06

2 Answers 2

1

You have an incorrect syntax while setting the count, for running nested commands in bash you need to use command-substitution using $(..) which runs the commands in a sub-shell and returns the restult

count=$(ls -- "$directory" | wc -l)

But never parse ls output in scripts for any purpose, use the more general purpose find command

find "$1" -maxdepth 1 -type f  | wc -l 

Check more about what $(..) form Wiki Bash Hackers - Command substitution

Sign up to request clarification or add additional context in comments.

8 Comments

That should be ls -- "$directory" in case you're dealing with a directory whose name starts with -.
@melpomene: Not something I'm recommending as per my update, but will make the edit still
Thank you so much Inian, btw could you please tell me what "$" is? Why do we put $ in front of (ls.....)?
@YooSungKyung: You should go through the link I shared
Thanks! When I use count=$(ls -- "$directory" | wc -l), the counted files are 4 but it should be 3, does it also count any hidden files?
|
0
#!/bin/bash

directory=$1
count=`ls $directory | wc -l`

echo "$folder has $count files"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.