I want to combine multiple conditions in a shell if statement, and negate the combination. I have the following working code for a simple combination of conditions:
if [ -f file1 ] && [ -f file2 ] && [ -f file3 ] ; then
# do stuff with the files
fi
This works fine. If I want to negate it, I can use the following working code:
if ! ( [ -f file1 ] && [ -f file2 ] && [ -f file3 ] ) ; then
echo "Error: You done goofed."
exit 1
fi
# do stuff with the files
This also works as expected. However, it occurs to me that I don't know what the parentheses are actually doing there. I want to use them just for grouping, but is it actually spawning a subshell? (How can I tell?) If so, is there a way to group the conditions without spawning a subshell?
if ! [ -f file1 ] || ! [ -f file 2 ] || ! [ -f file3 ] ; then
but I'd like a more general answer.if [[ ! -f file1 ]] && [[ ! -f file2 ]]; then
if [ ! 1 -eq 2 ] && [ ! 2 -eq 3 ]; then echo yep; fi
and it works. I just always write tests with double-braces as a matter of habit. Also, to ensure it's notbash
, I further testedif /bin/test ! 1 -eq 2 && /bin/test ! 2 -eq 3 ; then echo yep; fi
and it works that way also.[ ! -e file/. ] && [ -r file ]
will drop directories. negate it as you like. of course, that's what-d
does.