-1

I'm trying to understand how to run commands from my user account in a script with root privileges. I've got this test script and the output is confusing me.

~$ cat test.sh

output:

#!/usr/bin/bash
su -c "whoami" user
su -c "echo $HOME" user

~$ sudo ./test.sh

output:

user
/root

Why does the first 'su' command seem to run as 'user' but the second seems to run as 'root'?

Cyrus
  • 84,225
  • 14
  • 89
  • 153
  • Stack Overflow is a site for programming and development questions. This question appears to be off-topic because it is not about programming or development. See [What topics can I ask about here](http://stackoverflow.com/help/on-topic) in the Help Center. Perhaps [Super User](http://superuser.com/) or [Unix & Linux Stack Exchange](http://unix.stackexchange.com/) would be a better place to ask. – jww Oct 01 '17 at 22:35
  • Also see [Pass arguments to a command run by another user](https://unix.stackexchange.com/q/156343/56041), [Quoting within $(command substitution) in Bash](https://unix.stackexchange.com/q/118433/56041) on [Unix & Linux Stack Exchange](http://unix.stackexchange.com/); [How do I use a Bash variable (string) containing quotes in a command?](https://superuser.com/q/360966/173513) on [Super User](http://superuser.com/), etc, – jww Oct 01 '17 at 22:37

1 Answers1

1

Double quotes expand shell variables. Try

echo su -c "echo $HOME" user

to see what I mean. It's the shell running the script that expands $HOME, which runs as root (from sudo ./test.sh). So what ends up being run is su -c 'echo /root' user.

You want

su -c 'echo $HOME' user

Here we pass echo $HOME unexpanded to su -c.

melpomene
  • 84,125
  • 8
  • 85
  • 148