Simple script problem

Hi everyone - I am sure this is a really simple problem but I'm a total noob at Linux scripting:

I wanted to create a script that allows me to compare the current week number to the contents of a text file in my home directory:

VAR1='date +%V'
  VAR2='cat /home/fred/file.txt'


  if $VAR1 = $VAR2
  then
  echo �equal�
  else
  echo �not equal�
  fi

Sadly its not working and I don't know why, can someone help me out :slight_smile:

Many thanks

FR

You have to put your comparison in .
like this,

Also confirm that while assigning the variable, it should be between tilds(``)..

Also it's usually a good idea to add double quotes around the values; you will get very confusing error messages if either of the variables would turn out to contain an empty string (or a vast array of other possible problematic values).

if [ "$VAR1" = "$VAR2" ]

In real-world scripts, you frequently see a leading X added to the values, to guard against some of the remaining problematic scenarios (if $VAR1 has a value containing a dash as the first character, for example).

if [ X"$VAR1" = X"$VAR2" ]

For these reasons, I personally tend to recommend case over if for string comparisons.

To retrieve the week number of the file you can do something like:

VAR1='date +%V'

# get the week number of the file:

file_date=`stat -c "%y" file | cut -d " " -f1`
VAR2=`date +%V -d $file_date`

if [ "$VAR1" = "$VAR2" ]; then
....
else
....
fi

Regards

You should still use backticks for VAR1, too (ASCII 96, not regular apostrophes).

I was under the impression that the OP really did want to compare against the contents of the file, not the date on which the file was actually changed.

Right, I just copied the line of the OP, not realising that he used single quotes.

Regards