Shell script: if multiple conditions
You are missing some spaces, for example [!
must be [ !
and "]
must be " ]
look to the corrected code:
#!/bin/bash
if
[ ! -d "/home/unix/POSTagger2" ] ||
[ ! -d "/home/unix/POSTagger2/stanford-parser-full-2015-12-09" ] ||
[ ! -d "/home/unix/POSTagger2/stanford-corenlp-full-2015-12-09" ]
then
echo "Nope"
fi
Another way for your code:
#!/bin/bash
for dir in "/home/unix/POSTagger2" "/home/unix/POSTagger2/stanford-parser-full-2015-12-09" "/home/unix/POSTagger2/stanford-corenlp-full-2015-12-09"; do
if [ ! -d "$dir" ]; then echo nope ; break; fi
done
You need a space between the [
and the !
for things to work correctly. This is because [
is implemented as shell-builtin command (it even used to be a separate exectuable /usr/bin/[
).
You can also use:
if [ ! -d "/home/unix/POSTagger2" -o ! -d "/home/unix/POSTagger2/stanford-parser-full-2015-12-09" -o ! -d "/home/unix/POSTagger2/stanford-corenlp-full-2015-12-09") ] ; then
echo "Nope"
fi
Bash offers an alternative [[
that is implemented as en expression. [[
uses &&
, ||
, etc. instead of -a
, -o
as operators.
if [[ ! (-d "/home/unix/POSTagger2" && -d "/home/unix/POSTagger2/stanford-parser-full-2015-12-09" && -d "/home/unix/POSTagger2/stanford-corenlp-full-2015-12-09") ]] ; then
echo yes
fi
Edit: Thanks to comments from @LucianoAndressMartini and @pabouk for important corrections to my understanding.