I am trying to create a function which returns 0 or 1 (i.e. true or false) and takes an argument, then create a variable in another which stores the results of that function. Finally check if that variable is 0 or 1 (true or false)
Here is a sample of what I am attempting
#!/bin/bash
_has_string() {
if [ $1 == "string" ];
return 0
else
return 1
fi
}
_my_func() {
var=$(_has_string "string")
if [ $var == "0" ]; then
echo "var contains string"
else
echo "var does not contain string"
fi
}
_my_func
I have tried a few variations of this and can not seem to find a way to get it to work. All of my variations basically just return the $var
as nothing. Not a 0. Not null. Literally it is just blank.
Best Answer
You confuse output with the exit code.
You should also quote your variables; and
_has_string
can be simplified: