3

This question has been asked before, but I can't seem to get it work.

One of the solutions I tried is using here-document. I used the following code:

#!/bin/bash
su - mv2 <<EOSU
    DELIVER_BRANCH="development"
    echo ${DELIVER_BRANCH}
    exit;
EOSU

I tried the above code, bit echo ${DELIVER_BRANCH} doesn't print anything.

2
  • you can use su - USER -c 'echo XXX'
    – Rabin
    Commented Apr 6, 2016 at 10:32
  • I think su does not work well when piping commands in. Maybe stdin is not used or used in some other way (could not find something in the man page). But as @Rabin said you can pass short shell scripts via the -c option: su -c 'DELIVER=foo; echo $DELIVER; command1; command2 ...'
    – Lucas
    Commented Apr 6, 2016 at 12:05

1 Answer 1

8

You want:

#!/bin/bash
su - mv2 <<'EOSU'
    DELIVER_BRANCH="development"
    echo "$DELIVER_BRANCH"
    exit;
EOSU

Note the single quotes around the first EOSU. If you omit them, the heredoc undergoes $-interpolation before being passed, which means that "$DELIVER_BRANCH" gets replaced with the current (to the shell invoking su) content of $DELIVERY_BRANCH, which is empty:

DELIVERY_BRANCH=production
cat <<'EOSU'
    DELIVER_BRANCH="development"
    echo "$DELIVER_BRANCH"
    exit;
EOSU

prints

DELIVER_BRANCH="development"
echo "$DELIVER_BRANCH"
exit;

whereas

DELIVERY_BRANCH=production
cat <<EOSU
    DELIVER_BRANCH="development"
    echo "$DELIVER_BRANCH"
    exit;
EOSU

prints

DELIVER_BRANCH="development"
echo production
exit;
0

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.