LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Suse/Novell (http://www.linuxquestions.org/questions/suse-novell-60/)
-   -   multiple expression if statement (http://www.linuxquestions.org/questions/suse-novell-60/multiple-expression-if-statement-928486/)

s_linux 02-09-2012 09:15 AM

multiple expression if statement
 
Hello All,
I wanted to use multiple expressions in if statements and checking to see if my command syntax is right.

condition is if filesize greterthan 3mb and fileid not equal to 1234&2345.
fileid is basically file. I wanted to see if any of the file size is more than 3mb except for those two files.

command is

Quote:

if [ "${size}" -ge "3145728" -a "${fileID}" -ne "1234" ];then
if [ "${size}" -ge "3145728" -a "${fileID}" -ne "2345" ] ;then

Any help appreciated.

Thanks

acid_kewpie 02-09-2012 09:33 AM

as long as you are on bash, use the [[ notation, not the older, clunkier [, it's better in many many ways:

if [[ 1 -eq 1 && 3 -eq 3 ]]; then echo yes; fi

David the H. 02-11-2012 05:49 AM

What acid_kewpie said. The old brackets are not really designed for complex evaluations. If you must use them, however, use multiple individual tests instead of -a/-o.

Code:

if [ "$size" -ge 3145728 ] && { [ "$fileID" -ne 1234 ] || [ "$fileID" -ne 2345 ]; }; then
The newer double-bracket test is much more robust and convenient when it comes to complex conditions. You can more easily do expression grouping, for one thing.
Code:

if [[ "$size" -ge 3145728 && ( "$fileID" -ne 1234 || "$fileID" -ne 2345 ) ]]; then
But actually, when you're doing integer comparisons like this, arithmetic evaluation brackets are even better.

Code:

if (( size >= 3145728 && ( fileID != 1234 || fileID != 2345 ) )); then
This still may not be the best solution, though. It depends on how you're generating the input list of course, but I would personally see if I could eliminate one of the conditions from the input itself during that or some other earlier step, if possible.

acid_kewpie 02-11-2012 06:21 AM

Quote:

Originally Posted by David the H. (Post 4599632)
The newer double-bracket test is much more robust and convenient when it comes to complex conditions. You can more easily do expression grouping, for one thing.
Code:

if [[ "$size" -ge 3145728 && ( "$fileID" -ne 1234 || "$fileID" -ne 2345 ) ]]; then

Also there is no need for quote marks as bash deals with variable substitution itself, rather than leaving until after literal string replacement and globbing occurs.

David the H. 02-11-2012 08:02 AM

True, one of the benefits of the new test is that there's no word-splitting done on variable expansions. But it never hurts to keep up the practice anyway, even when not strictly necessary. Places like this where it's safe to leave them off are relatively rare.


All times are GMT -5. The time now is 05:43 AM.