Tom
Tom

Reputation: 1618

Bash comparing values

I'm getting the size of a file from a remote webserver and saving the results to a var called remote I get this using:

remote=`curl -sI $FILE | grep -i Length | awk '/Content/{print $(NF-0)}'`

Once I've downloaded the file I'm getting the local files size with:

local=`stat --print="%s" $file`

If I echo remote and local they contain the same value.

I'm trying to run an if statement for this

if [ "$local" -ne "$remote" ]; then

But it always shows the error message, and never advises they match.

Can someone advise what I'm doing wrong.

Thanks

Upvotes: 1

Views: 67

Answers (1)

Gordon Davisson
Gordon Davisson

Reputation: 125788

curl's output uses the network format for text, meaning that lines are terminated by a carriage return followed by linefeed; unix tools (like the shell) expect lines to end with just linefeed, so they treat the CR as part of the content of the line, and often get confused. In this case, what's happening is that the remote variable is getting the content length and a CR, which isn't valid in a numeric expression, hence errors. There are many ways to strip the CR, but in this case it's probably easiest to have awk do it along with the field extraction:

remote=$(curl -sI "$remotefile" | grep -i Length | awk '/Content/{sub("\r","",$NF); print $NF}')

BTW, I also took the liberty of replacing backticks with $( ) -- this is easier to read, and doesn't have some oddities with escapes that backticks have, so it's the preferred syntax for capturing command output. Oh, and (NF-0) is equivalent to just NF, so I simplified that. As @Jason pointed out in a comment, it's safest to use lower- or mixed-case for variable names, and put double-quotes around references to them, so I did that by changing $FILE to "$remotefile". You should do the same with the local filename variable.

You could also drop the grep command and have awk search for /^Content-Length:/ to simplify it even further.

Upvotes: 4

Related Questions