I have tried countless ways to get what I want, but nothing seems to work. I always end up with something like 2:not found
.
I want to capture the output of a command, and then test if it equals "!", like so:
function test() {
local testv=$(command) 2>/dev/null
if [ $(#testv) == "!" ]; then
echo "Exclamation mark!"
else
echo "No exclamation mark."
fi
}
How should I rewrite the code above to avoid the error test:2: = not found
?
This should work:
if [ $testv = '!' ]; then
There were several problems here:
$(...)
runs a command and substitutes its output; you want to substitute a variable value, so use $var
or ${var}
.#
was doing there. ${#var}
will get the length of $var, but that's not what you want here.test
command (which [
is a synonym for) doesn't understand ==
, so use =
(if you're a C programmer that'll look wrong, but this is shell not C)."!"
doesn't do what you expect. I used '!'
to make sure the exclamation mark couldn't be interpreted as a history option.Alternately, you could use [[ ]]
instead of [ ]
, since it understands ==
(and has somewhat cleaner syntax in general):
if [[ $testv == '!' ]]; then
BTW, I'm trusting from the tag that this script is running in zsh; if not, the syntax will be a bit different (basic shells don't have [[ ]]
, and anything other than zsh will do unwanted parsing on the value of $testv unless it's in double-quotes). If you're not sure (or want it to be portable), here's a version that should work in any posix-compliant shell:
if [ "$testv" = '!' ]; then