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.

  • you can use su - USER -c 'echo XXX' – Rabin Apr 6 '16 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 Apr 6 '16 at 12:05
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;
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.