0

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?

Akiiino
  • 1,050
  • 1
  • 10
  • 28
  • not sure what is wrong, but you can start by using this syntax `thehash=$(cksum "$1")` instead of ``thehash="`cksum $1`"`` .. – Sundeep Oct 08 '16 at 12:58
  • see http://unix.stackexchange.com/questions/131766/why-does-my-shell-script-choke-on-whitespace-or-other-special-characters/131767#131767 and http://mywiki.wooledge.org/BashFAQ/082 – Sundeep Oct 08 '16 at 12:59

1 Answers1

3

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

Community
  • 1
  • 1
Eric Renouf
  • 13,950
  • 3
  • 45
  • 67
  • Oh! I've tried using brackets, but they didn't help; I did not pay attention and didn't notice that they are separated with spaces! Bash is complicated... Anyway, thank you so much! – Akiiino Oct 08 '16 at 13:05
  • 1
    @Akiiino http://www.shellcheck.net/ is very useful then and don't forget to quote your variables... ex: `"$1"` – Sundeep Oct 08 '16 at 13:06
  • @Akiiino white space is often important in bash, that's what it uses to tokenize (a.k.a., word splitting) – Eric Renouf Oct 08 '16 at 13:06
  • 1
    @Sundeep good point about quoting the variables. shellcheck.net is great and highlighted the backticks question, but it didn't catch this particular problem because the code was valid syntax, it just wasn't semantically correct – Eric Renouf Oct 08 '16 at 13:07