Files and directories can have newlines in their names, so you cannot "just" use wc -l
as you are doing.
If you want a script that takes a parameter and recursively counts files and directories, you should use:
#!/bin/bash
echo -n 'total directories:'; find "$1" -type d -printf \\n | wc -l
echo -n 'total files:'; find "$1" -type f -printf \\n | wc -l
And call the script by providing the directory as commandline argument:
./your_script_name /home/e_g_your_home_dir.
Although, short, the above is of by one for the directories (unless you consider a directory to be "in" itself), you can also replace wc -l
with something that can handle NUL-terminated "lines" and
use -print0
#!/bin/bash
echo -n 'total directories:'; find "$1" -type d -print0 | python -c "import sys; print len(sys.stdin.read().split('\0'))-2"
echo -n 'total files:'; find "$1" -type f -print0 | python -c "import sys; print len(sys.stdin.read().split('\0'))-1"
If you don't want to do this recursively (only counting the files/directories in the directory you specify and not the ones in a directory that is in the directory you specify) you should add -maxdepth 1
after the $1
parameter.
find
. Usingwc -l
will be incorrect if there are any files/directories with newlines in their name. – Anthon May 04 '15 at 12:47-type f
) and directories (as selected as-type d
) are just 2 of many types of file one Unix systems. What about symlinks, fifos, devices, doors, sockets... – Stéphane Chazelas May 04 '15 at 13:24