0

I'm struggling with storing the return value (0 or 1) of my function in a variable. Whatever I try, $var ends up being empty or I run into error messages. Here is my specific code:

function screen_exists() {
        if screen -list | grep -q "${1}"; then
          return 0
        else
          return 1
        fi
    }

VAR=$(screen_exists "${PLAYER_SCREEN_NAME}")
echo ${VAR}

I've also tried with a super simple function that always returns 0, but same outcome.

Noniq
  • 369
  • 1
  • 5
  • 13
  • @Cyrus That was a copy&paste error on my part. I'm sorry, fixed it! – Noniq Sep 29 '19 at 14:02
  • 1
    Your function can just be `screen_exists () { screen -list | grep -q "$1"; }`. The return code of the function will be `0` (success) if `grep` finds a match. You should follow this convention, rather than returning `1` for success and `0` for failure. It will allow you to use the function like `if screen_exists "name"`. – Tom Fenech Sep 29 '19 at 17:37

1 Answers1

2

$(...) is command substitution syntax that is used to capture output of given command. If you want to store return value of a function then use $?:

screen_exists() {
    screen -list | grep -q "$1"
    # implicit here is: return $?
}

screen_exists "${PLAYER_SCREEN_NAME}"
ret=$?

Also note that this function will return 1 if grep doesn't find search patter and 0 if it is success which is the standard norm in shell utilities.

anubhava
  • 761,203
  • 64
  • 569
  • 643
  • 1
    Thanks a lot, I didn't know `$?` was a thing. All my google searches suggested something like `ret=$(function)` and I tried to tweak that according to my needs. – Noniq Sep 29 '19 at 14:05
  • 1
    Thanks @TomFenech, both valid points. I have added them in my answer. – anubhava Sep 30 '19 at 04:43