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.