Simple echo problem

Hey all! I'm in an intro to UNIX class at university, and we've just began writing scripts. Naturally I can't get it to do what I want.

Basic script as follows:

COMPARE1=`ls|wc -l`
tar czf archive.tgz  ~/path/to/file
COMPARE2=`tar tvzf archive.tgz|wc -l`

      if [ $COMPARE1 -eq $COMPARE2 ]
      then
        echo "They are the same."
      else
        echo "They are not the same."
      fi

So basically making sure that there are the same amount of files in the directory and in the archive. HOWEVER! The script isn't storing my variables. When I close the script and echo either of those variables it gives me a blank line instead of the word count. And obviously the script echos that they aren't the same.

Help!

What do you mean by 'close the script'?

The variables are only valid inside the script.

1 Like

What happens when the listing and the tarball refer to the same directory?

path="~/path/to/file"
COMPARE1=$(ls  $path|wc -l)
tar czf archive.tgz  $path
COMPARE2=`tar tvzf archive.tgz|wc -l`
if [ $COMPARE1 -eq $COMPARE2 ]
      then
        echo "They are the same."
      else
        echo "They are not the same."
fi

As Corona points out above you don't have access to a variable once its parent process is finished. You can of course add debug statements to your script to help you find out what's going wrong.

... unless you source the script:

$ . /path/to/myScriptFile.sh
$ echo $COMPARE1 $COMPARE2

Well that explains a lot! The more you know...

And the script is telling me the variables aren't equal because a tar file includes the directory, and an ls doesn't.

tar will list the base directory as well I think:

tar -vtf filename
base_folder/
base_folder/file1
base_folder/file2
...

while ls would only list file1, file2, ...

tar also recurses, while ls doesn't.

How about find instead of ls? It prints output more like tar does...

find /path/to/folder | wc -l

It also has powerful options for filters and ways to do things using the filenames it finds, but if all you want is the listing...

1 Like

And just like that... hours and hours of work is fixed. That's what I get for being a noob haha :wall:

Many thanks!

Everyone has to start somewhere. Now that you know of find, you might find tons of uses for it.