3

I'm looking to get the number of subdirectories within a directory and compare that with a predefined number.

Ex:

cd /Applications/
x=echo ls -d */ | wc -l | sed 's/^ *//g'
y="52"

if [ "$x" == "$y" ]; then
    echo "equal"
else
    echo "not equal"
fi

It will give me a number for x (52 in my case), but will always say "not equal". What am I doing wrong? Any help would be greatly appreciated.

Thanks

3
  • Actually, it will not give you a number. Commented Dec 11, 2013 at 0:21
  • consider using the [[ ]] - double-square-bracket form of predicates, unless you need compatibility with shells which don't have this extension, for the reasons given here: stackoverflow.com/questions/13542832/… Commented Dec 11, 2013 at 0:23
  • I do know this will not give me a number per se, but I am comparing two strings; unless I'm missing something? I have tried double-square brackets as well unfortunately. Commented Dec 11, 2013 at 0:57

2 Answers 2

3

For bash, do this:

cd /Applications/
dirs=( */ )   # dirs is an array with the names of directories here
if (( ${#dirs[@]} == $y )); then
    echo "equal"
else
    echo "not equal"
fi
Sign up to request clarification or add additional context in comments.

Comments

0

Replace

x=echo ls -d */ | wc -l | sed 's/^ *//g'

with:

x="$(ls -d */ | wc -l | sed 's/^ *//g')"

Explanation: When you write x=echo ls -d */ ..., bash thinks that you mean to temporarily set the the variable x to a value of "echo" and then run the ls command. You, instead, want to run the command s -d */ | wc -l | sed 's/^ *//g' and save the output in x. The construct x=$(...) tells bash to execute whatever was in the parens and assign the output to x.

Also, bash's [ command does not accept ==. Use = for string comparison. However, you really want mathematical comparison. So use '-eq':

  if [ "$x" -eq "$y" ]; then

2 Comments

Thanks for the quick reply. I notice that it is no longer printing the value for x, but it's still not evaluating my comparison properly. 52 == 52 is showing not equal. Unless I'm still missing something?
I originally started with 'eq' and then '=', but both result in not equal. Thanks again.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.