Find the answer to your Linux question:
Results 1 to 3 of 3
I was trying to make write a shell script that would compare the number of files in 2 given directories.I 've come up with this : Code: #!/bin/bash read -p ...
  1. #1
    Just Joined!
    Join Date
    Jun 2008
    Posts
    25

    Script to compare directories

    I was trying to make write a shell script that would compare the number of files in 2 given directories.I 've come up with this :
    Code:
    #!/bin/bash
    read -p "enter the first directory: " NAME1
    read -p "enter the second directory: " NAME2
    x=$(ls "$NAME1" |wc -l)
    y=$(ls "$NAME2" |wc -l)
    if [ "$x -gt $y" ] ; then
    echo "first directory has more files"
    elif [ "$x -eq $y" ] ;  then
    echo "direcories have the same number of files"
    else
    echo "second directory has more files"
    fi
    My problem here is that the result is always "first directory has more files" even if that's not true.Where is my mistake or what should I do..?Thanks in advance..

  2. #2
    Linux Guru
    Join Date
    Nov 2004
    Posts
    6,110
    I haven't got a Linux box near me to check, but it would seem the quotation within the if test is incorrect. You are testing if the string, well...exists. A negative return is not likely from that the way it's phrased now. Try doing it this way with each variable quoted :-
    Code:
    #!/bin/bash
    read -p "enter the first directory: " NAME1
    read -p "enter the second directory: " NAME2
    x=$(ls "$NAME1" |wc -l)
    y=$(ls "$NAME2" |wc -l)
    if [ "$x" -gt "$y" ] ; then
    echo "first directory has more files"
    elif [ "$x" -eq "$y" ] ;  then
    echo "direcories have the same number of files"
    else
    echo "second directory has more files"
    fi

  3. #3
    Just Joined!
    Join Date
    Jun 2008
    Posts
    25
    thanks my friend...it works great.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...