Akiiino
Akiiino

Reputation: 1100

Can't check checksum in bash --- apparently, wrong syntax?

I have this bit of code, that is supposed to call reload if current file ($1) is changed:

thehash="`cksum $1`"

while true
do
    curhash="`cksum $1`"
    if "$curhash" -ne "$thehash"; then
        reload
    fi
    ...
done

tl;dr: it doesn't work.

Since I am not very experienced with bash, I can't figure out what did I do wrong. I get this error:

58003725 834183 main.pdf: command not found

Apparently, bash is trying to execute curhash? How do I fix this?

Upvotes: 0

Views: 211

Answers (1)

Eric Renouf
Eric Renouf

Reputation: 14510

You need brackets around your condition in if or to use the test command, so it should be

if [[ "$curhash" != "$thehash" ]]; then

and note that -ne is for integer comparison, != is for string comparison

Without the [[ or test the variable gets expanded and that becomes a command to run, which is why it was trying to execute the output of cksum: the content of curhash was being treated as a command.

Also, as @Sundeep mentioned the more often preferred way to get the output from the subshell is to use $(...) instead of the backticks. here is a good answer talking about that

Upvotes: 3

Related Questions