5

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.

1
  • 1
    Note: In Bash if comparing strings, you must use double brackets like [[ $1 == "string" ]]; May 28, 2018 at 7:02

3 Answers 3

13

You confuse output with the exit code.

_my_func() {
  if _has_string 'string'; then

You should also quote your variables; and _has_string can be simplified:

_has_string() {
    [ "$1" = 'string' ]
}
1
  • You are correct, I was confusing output with exit codes. Your solution works. As I had mentioned in original post I tried many variations, though I think the missing one that I kept getting wrong was putting square brackets around the if _has_string 'string' conditional. Removing the brackets made it worked. This is why I was attempting to store it in a variable. Your approach removes the need for creating an unneeded variable. Thank you. May 29, 2018 at 20:21
6

$(...) returns the output of the command: the things sent to stdout. You want the exit code. After a process (or, in your case, function) exits in a bash script, the special variable $? is set to the exit code.

So rather than

var=$(_has_string 'string')
...

consider

_has_string 'string'
var=$?
...
1
  • 2
    Or even if _has_string 'string'; then ... May 27, 2018 at 20:42
0

As others already pointed out, what you need to merely use the function within the if statement. Here's something you might not have known:

A function can be treated as a form of compound command. And according to bash manual [[ is one of the operators that can be used in construction of a compound command. Thus, your function _has_string() can be implemented as so:

$ _has_string()[[ "$1" = "string" ]]
$ if _has_string "string"; then echo "YES"; fi
YES

Of course, this is in no way portable, because of the [[ operator. But we can make use of ( ) or {}. Here's for example how this works in /bin/dash:

$ _has_string()( [ "$1" = "string" ]; )
$ if _has_string "string"; then echo "YES"; fi
YES
$ if _has_string "nope" ; then echo "YES"; fi                             
$ 
1
  • 1
    I wouldn't use the parenthesis in that function definition, they run a subshell which is in no way needed here.
    – ilkkachu
    May 29, 2018 at 11:28

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .