简体   繁体   中英

multiple conditions in bash shell

I have this piece of code in Bash, The goal is to compare two files and if files matches and also no force argument is passed, then exit. Other way it should continue...

But I got this error [: :=: unexpected operator when I run with no argument and script is not stopped as expected, When I pass force argument it works OK. Any Idea please?

if    cmp -s  file1  file2  &&  [ $1 != "-f" ] ;  then 
"do something"
exit 1
else "do something"
fi

[... ] is just a normal command, essentially equivalent to test . As such, if you pass an unquoted empty variable (like $1 when no arguments are provided to your program), it will try to run [ != "-f" ] , which gives that error, since you need two sides to compare with != .

To solve this, you can either use [[... ]] (which requires bash , not being POSIX compatible), which does not make unquoted variables "disappear", or you can also quote your variable to keep it POSIX compatible:

cmp -s file1 file2 && [[ $1 != "-f" ]]
cmp -s file1 file2 && [ "$1" != "-f" ]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM