Reputation: 33
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
Upvotes: 3
Views: 107
Reputation: 246744
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
Upvotes: 3
Reputation: 113814
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
Upvotes: 0