I am attempting to compare two directories and then update the log file after determining what files are different between the two, but I keep getting error messages saying that it expects an integer result in the line [ if $userinput -eq $userinput.log ]. Is there a way to compare these two that I am missing? Here is the script I have written.
userinput=$1
if [ ! -d "$userinput" ];
then
echo "Usage: dirlog.sh directory_name" 1>&2
exit 0
else
if [ ! -f "$userinput.log" ];
then
ls -l > $userinput.log
echo ".logfile created for $userinput"
elif [ -f "$userinput.log" ];
then
if [ $userinput -eq $userinput.log ]; #if they are different
then
differences=diff -rq $userinput $userinput.log
for file in $differences
do
echo "$file missing from directory $userinput"
done
else
echo "no files missing from directory $userinput"
fi
#Update this no matter what
ls -l > $userinput.log
echo "logfile updated for directory $userinput"
fi
fi
You can compare two directories with the diff -r
command. This will show you all files that differ, which files are missing from one directory to another. The --brief
option or --summary
option will simply list the differences and not the content of the files.
Now, about your if [ $userinput -eq $userinput.log ];
...
In shell, a variable could hold numeric or could hold alphanumeric data. Let's take something like this:
foo="0456"
bar="456"
In the above, $foo
and $bar
could be strings or numbers. If I think of them as numbers, they're equal. However, if they are strings, they're not equal.
Here's another example:
foo="123"
bar="45"
Which is greater? Again, it depends whether $foo
and $bar
are being treated as strings or numbers. If I treat them numerically $foo
is greater. However, if I treat them as text strings, $bar
is greater because the first character of $bar
which is 4
comes after the first character of $foo
, 1
.
So, how does bash know whether I want numeric or string comparison? Simple, Bash provides me with two different sets of comparison operators. One is for strings and one is for text:
String Numeric
------ -------
Equals = -eq
Greater Than > -gt
Less Than < -lt
Not equals != -ne
Greater Than/Equals >= -ge
Less Than/Equals <= -le
In your case, you want to compare two strings and you're using -eq
. This is why you're getting the error that the -eq
operator expects numeric results. By the way, if you're using Bash or Kornshell, you should go ahead and use the doubled square brackets [[ ... ]]
. These are less error prone and have a few more nice features such as pattern matching:
if [[ $userinput == "$userinput.log" ]]
However, I really recommend you to use he diff -r --brief
command for comparing two directories.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.