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

  • Actually, it will not give you a number. – user2719058 Dec 11 '13 at 00: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: http://stackoverflow.com/questions/13542832/bash-if-difference-between-square-brackets-and-double-square-brackets –  Dec 11 '13 at 00: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. – user3089044 Dec 11 '13 at 00:57

2 Answers2

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
glenn jackman
  • 238,783
  • 38
  • 220
  • 352
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
John1024
  • 109,961
  • 14
  • 137
  • 171
  • 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? – user3089044 Dec 11 '13 at 00:24
  • I originally started with 'eq' and then '=', but both result in not equal. Thanks again. – user3089044 Dec 11 '13 at 00:44