Reputation: 21
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!
Upvotes: 1
Views: 822
Reputation: 148
#!/bin/bash
directory=$1
count=`ls $directory | wc -l`
echo "$folder has $count files"
Upvotes: 0
Reputation: 85895
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
Upvotes: 1