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.

Timo Ernst
  • 15,243
  • 23
  • 104
  • 165

2 Answers2

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"
kvantour
  • 25,269
  • 4
  • 47
  • 72
-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

Kubator
  • 1,373
  • 4
  • 13
  • This code snippet does not produce any output on my machine. This doesn't seem really portable. – Aserre Dec 03 '18 at 13:51
  • What platform are You on. who command is under GNU core utilities: https://www.gnu.org/software/coreutils/manual/html_node/who-invocation.html#who-invocation – Kubator Dec 03 '18 at 13:55
  • 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 – Aserre Dec 03 '18 at 14:02