-1

i am confused..

i just make if file does not exist OR md5 sum is wrong

something like this

md5=20ffa23fbb589484d03d79608fe8d2ad
if ! -f /tmp/1.txt  || echo -n ${md5} /tmp/1.txt | md5sum --status --check -
then
 ....
fi

how write valid syntax?

Cyrus
  • 84,225
  • 14
  • 89
  • 153
Anton Shevtsov
  • 1,279
  • 4
  • 16
  • 34
  • Possible duplicate of [How to do a logical OR operation in shell scripting](https://stackoverflow.com/q/4111475/608639), [Simple logical operators in Bash](https://stackoverflow.com/q/6270440/608639), [Groups of compound conditions in Bash test](https://stackoverflow.com/a/14965071/608639), etc. – jww Apr 22 '19 at 07:19
  • @jww The second one is pretty close, but doesn't cover mixing conditional expressions with other types of commands (which is important in this question). – Gordon Davisson Apr 22 '19 at 07:25

2 Answers2

3

The things in an if condition are commands (like echo ... | md5sum ...), not conditional expressions (like -f /tmp/1.txt). In order to use a conditional expression, you need to use the test command:

if ! test -f /tmp/1.txt  || echo -n ${md5} /tmp/1.txt | md5sum --status --check -

or its synonym [ (note that it expects a "]" as its last argument, so it looks like funny parentheses):

if ! [ -f /tmp/1.txt ]  || echo -n ${md5} /tmp/1.txt | md5sum --status --check -

or in bash or zsh, you can use [[ ]] (which isn't a regular command, and has somewhat cleaner syntax for more complex conditions):

if ! [[ -f /tmp/1.txt ]]  || echo -n ${md5} /tmp/1.txt | md5sum --status --check -

BTW, I'm pretty sure you also want to negate the md5 status check, so you need another "!" to negate that as well:

if ! [[ -f /tmp/1.txt ]]  || ! echo -n ${md5} /tmp/1.txt | md5sum --status --check -

Edit: I'd also recommend skipping the -n option on echo -- it doesn't seem to be necessary, and it isn't portable. So some versions of echo will just print "-n" as part of their output, which will confuse md5sum. I had a bunch of scripts that used echo -n, and had to rewrite them in a panic after a system update changed the behavior of echo... so ever since then I've avoided it like the plague, and used printf when I need something like that.

Gordon Davisson
  • 118,432
  • 16
  • 123
  • 151
1
md5hash=031f8c1dba9b8ca6890a7f3dc13428f2
[ ! -f /tmp/1.txt ] || md5arr=( $(md5sum /tmp/1.txt) ) && [ ${md5arr[0]} == $md5hash ]
[ $? -ne 0 ] && echo "no file or file changed"
sjsam
  • 21,411
  • 5
  • 55
  • 102