I know in shell the exclamation mark can invert the outcome of condition. Here I wanna use it to test variable is true or false .
#! /bin/bash
bat=false
if [
if
tests the results of commands and can't directly test the values of variables. In this case you're using it in conjunction with the test
/[
command, which is an ordinary command and can be used anywhere.
[ -f ./foo.txt ] && echo "foo.txt exists"
or equivalently
test -f ./foo.txt && echo "foo.txt exists"
both test whether a file exists at the path ./foo.txt
.
Depending on what you mean by "true", you can use the test
or [
shell builtin to determine whether a variable is equal to another, and for some other functions like testing whether a directory or file exists.
You can use if [ -z "$variable" ]; then ...; fi
to check whether a variable is the empty string.
If you want to check whether the variable is set at all, even to an empty value, you can use parameter expansion [ -z "${var+x}" ]
. It only evaluates to true
(meaning has exit status zero) when var
is undefined.
If you want to compare a variable against a fixed string you can use [ "$var" = "some-string" ]
or use case
e.g.
case "$var" in
some-string)
dostuff
;;
esac
Note that you can negate that the result of test
/[
using !
.
if ! [ -z "$var" ]; then
do-something
fi
Does negate the condition.
However, !
is also valid as an argument to test
/[
if [ ! -z "$var" ]; then
do-something
fi
means the same thing.