0

I have a simple script like this to write into a file:

#!/bin/bash
sudo bash -c 'cat <<EOT >> foo/bar.txt
  Hello ${USER}
EOT'

When I run it the content of foo/bar.txt is:

Hello root

My username:

$ whoami
timo

So I expected it to output "Hello timo". The result of "Hello root" does make sense though since I run it through the sudo command.

Is there any way to access the user name of the "outer bash" somehow, so it outputs "Hello timo" instead of "Hello root"?


Update 2018-12-04

I'd like to point out that I saw that other post before opening this question and the suggestions from there didn't work (who am i and logname). The only option that actually worked is the accepted answer from this thread by kvantour using ${SUDO_USER}. In the other post it was suggested that this wouldn't work:

$SUDO_USER doesn't work if you are using sudo su -

So, no need to downvote imho.

0

2 Answers 2

2

You might want to try:

#!/usr/bin/env bash
sudo bash -c 'cat - <<EOF >> foo/bar.txt
  Hello ${SUDO_USER}
EOF'

sudo utilizes the following environment variables:

  • SUDO_GID: Set to the group ID of the user who invoked sudo.
  • SUDO_USER: Set to the login name of the user who invoked sudo.

source: man sudo

If you cannot use SUDO_USER and it has to be USER, then you have to double quote your string your parse to bash. Double quotes will still substitute the variables:

#!/usr/bin/env bash
sudo bash -c "cat - <<EOF >> foo/bar.txt
  Hello ${USER}
EOF"
Sign up to request clarification or add additional context in comments.

2 Comments

Timo is mentioning that he is running command under sudo, so he needs to access user who called sudo, if understood well.
Works! Perfect answer, thanks!
-2

This should work for You. Replace ${USER} with this:

$(who -m | cut -d' ' -f1)

who -m provides further login info that's why cut first field

3 Comments

This code snippet does not produce any output on my machine. This doesn't seem really portable.
What platform are You on. who command is under GNU core utilities: gnu.org/software/coreutils/manual/html_node/…
OSX. It uses BSD utils. OP didn't indicate which distro they are running their script from, so assuming they are using a system compatible with GNU coreutils is a bit far fetched

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.