Other answers clarify why your command is not working, and some great suggestions as to how to test its result. I'd like to add one more.
$(command)$? appends the exit code
You can do this using a combination of command substitution and exit code checking, all in one line. It will append the exit code to the output as a number.
check=$( grep -ci 'text' file.sh )$?
This is actually $(some command)
(get the string output of a command) immediately followed by $?
(get the exit code of the last command). To work, they have to be used together with no space.
Source: https://www.assertnotmagic.com/2018/06/20/bash-brackets-quick-reference/#-dollar-single-parentheses-dollar-q-
If there is any possibility of output, which is the case with most commands, you will have to suppress it using > /dev/null 2>&1
.
This may not be necessary if you're using a test command such as test -d <directory>
.
check=$( grep -ci 'text' file.sh > /dev/null 2>&1)$?
You could use a function to abstract this away:
e() {
$@ > /dev/null 2>&1
}
# Usage:
check=$(e grep -ci 'text' file.sh)$?
Testing the exit code
To use this later, test against zero (success):
[ $check -eq 0 ] && echo "passed" || echo "didn't pass"
[ $check -ne 0 ] && echo "didn't pass" || echo "passed"
Using an if/then/else construct, testing against zero (success):
if [ $check -eq 0 ]; then
echo "passed"
else
echo "didn't pass"
fi
if [ $check -ne 0 ]; then
echo "didn't pass"
else
echo "passed"
fi
Testing exit code directly
Using exit
within a (
subshell)
will produce a proper exit code from the number which you can use directly:
(exit $check) && echo "check passed" || echo "check didn't pass"
! (exit $check) && echo "check didn't pass" || echo "check passed"
Using an if/then/else construct, using exit code directly:
if (exit $check); then
echo "passed"
else
echo "didn't pass"
fi
if ! (exit $check); then
echo "didn't pass"
else
echo "passed"
fi
Using return
instead of exit
will also work in some shells - zsh included (but not bash).
Getting fancy
If you want to simplify even more, use this function:
t() { return $1; }
and now you can test like this:
t $check && echo "passed" || echo "didn't pass"
! t $check && echo "didn't pass" || echo "passed"
$?
right after command is finished.