I realize this is a simple question, but I am finding a hard time getting an answer due to the finnicky syntax requirements in bash. I have the following script:
The test
shell builtin [
supports the arguments -a
and -o
which are logical AND and OR respectively.
#!/bin/sh
if [ -n "$1" -a -n "$2" ]
then echo "both arguments are set!"
fi
Here I use -n
to check that the strings are non-zero length instead of -z
which shows that they are zero length and therefore had to be negated with a !
.
" -n string True if the length of string is nonzero."
"-z string True if the length of string is zero."
If you are using bash
it also supports a more powerful type of test [[]]
which can use the boolean operators ||
and &&
:
#!/bin/bash
if [[ -n "$1" && -n "$2" ]]
then echo "both arguments are set!"
fi
In comments it was addressed that none of these samples show how to negate multiple tests in shell, here is an example which does:
#!/bin/sh
if [ ! -z "$1" -a ! -z "$2" ]
then echo "both arguments are set!"
fi