2

I am trying to do a IF..ELSE inside a heredoc. The heredoc is necessary because the set of commands need to be executed as a different user.

Unfortunately, the IF statement doesn't work as expected, and always jumps to the ELSE clause. When I remove the IF block from the heredoc and place it outside it works as expected.

It is probably a simple thing I'm missing, but I have no idea what.

rem=0
function1 () {
    su - user1 <<'DONE'
        if [[ "$rem" -eq 0 ]];
        then
            echo rem is even
        else
            echo rem is odd
        fi
DONE

}

function1

It echoes rem is odd.

ahron
  • 803
  • 6
  • 29
  • 1
    don't you get a syntax error using function like this? I would imagine you would need to `export rem` thou, and drop the `-` – Rorschach Aug 28 '19 at 07:59
  • thanks a lot! it works now... the exporting bit never occurred to me.. – ahron Aug 28 '19 at 08:29
  • @jenesaisquoi yes, you're right, `function` shouldn't be used like that, it was a mistake I made while changing my code for copying in here. fixed it now in the question. – ahron Aug 28 '19 at 08:33

1 Answers1

1

Change the 3rd line of your script with this:

su - user1 <<DONE

Notice the missing quotes around DONE. With quotes around the delimiter you basically deactivate the parameter substitution and the value of $rem is not what you expect it to be (just echo it and see). Without the quotes, the parameter substitution works.

Tested on a CentOS 7 with Bash 4.2.46.

See also a longer discussion here: Using variables inside a bash heredoc

Ciprian Stoica
  • 2,309
  • 5
  • 22
  • 36
  • if you do this, would later changes to `rem` have any effect on the result of the function call? – Rorschach Aug 28 '19 at 23:40
  • @jenesaisquoi I'm not sure what you mean. Give me a concrete example. Or better, open a new topic on this. – Ciprian Stoica Aug 29 '19 at 08:02
  • I wasn't sure if bash would evaluate the function definition only once, substituting the value of `rem` into the body, thus making all subsequent function calls return the same result, regardless of later changes to `rem` – Rorschach Aug 29 '19 at 08:10
  • after a quick test it would seem bash actually reevaluates the function with each call, however (surprising to me), so disregard my comment – Rorschach Aug 29 '19 at 08:11