Joe X
Joe X

Reputation: 79

using "wc -l" on script counts more than using on terminal

I'm making a bash script and it's like this:

#!/bin/bash
DNUM=$(ls -lAR / 2> /dev/null | grep '^d' | wc -l)
echo there are $DNUM directories.

the problem is, that when I run this line directly on the terminal:

ls -lAR / 2> /dev/null | grep '^d' | wc -l

I get a number.

But when I run the script it displays me a greater number, like 30 to 50 more.

What is the problem here?
Why is the "wc" command counting more lines when running it from a script?

Upvotes: 2

Views: 351

Answers (2)

mat1010
mat1010

Reputation: 847

To find the differences in your exact case I would suggest to run

#!/bin/bash
for r in 1 2; do
  ls -lAR / 2> /dev/null | grep '^d' > run${r}.txt 1> out${r}.txt
done
diff -Nura out1.txt out2.txt
rm -f out1.txt out2.txt

But as the most ppl. already said it would make sense to exclude directories like sys,proc ...

Upvotes: 0

karakfa
karakfa

Reputation: 67507

You may have different directory roots for the two runs. Instead of ls to find the directories only you can use this

find parent_directory -type d

and pipe to wc -l to count.

The /proc directory will have processes and treated as directories and will change from run to run. To exclude it from the count use

find / -path /proc -prune -o -type d | wc -l

Upvotes: 1

Related Questions