-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?

2

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

1
md5hash=031f8c1dba9b8ca6890a7f3dc13428f2
[ ! -f /tmp/1.txt ] || md5arr=( $(md5sum /tmp/1.txt) ) && [ ${md5arr[0]} == $md5hash ]
[ $? -ne 0 ] && echo "no file or file changed"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.