1

It's explained that if we using su with -c parameter it will pass the command to user's shell and execute it.

But in my environment, it totally ignore's the -c option and change to user's shell.

[root@mftf~]# su - demo -c "ls -la"

[demo@mftf~]$

but if I using -c without any command follow, it will show the error that -c need a argument, so it's not ignored.. I'm using RHEL 7.

2
  • 2
    Your command also works correctly for me (on a non-RHEL version of Linux). What is the login shell for demo?  Can you post the output for grep demo /etc/passwd, and, from user’s shell (demo$ ), ps -fp$$ and ps -fudemo? Sep 28, 2017 at 18:43
  • @Scott-СлаваУкраїні I wish you would have posted this as an answer. I experienced the same issue as OP described and for me the problem was the login shell of the user i wanted to become (ksh, it works with bash). Thanks, anyways.
    – jera
    Oct 17, 2023 at 7:28

2 Answers 2

3

When using - (or -l) you invoke an interactive login shell for the specified user.

Depending on what the shell initialization files do for the given user, the command may not be executed. For example, if they re-execute a shell using exec (without passing the command line parameters from the invoking shell), either directly or through something like tmux or ssh-agent, then the command string would be lost.

For example: I have

if tmux has-session; then
    exec tmux attach-session
else
    exec tmux
fi

... in my ~/.profile, which is why su -l me some_command won't execute some_command (instead, an interactive shell is started inside tmux).

To execute a command as another user using su just do

# su -c some_command username

From the Ubuntu su(1) manual:

-, -l, --login

Provide an environment similar to what the user would expect had the user logged in directly.


Or set up sudo and use

$ sudo -u user some_command
2
  • well thats bcoz profile is not loaded, so when you invoke su demo without - your current user cwd becomes cwd for user demo, so in this case /root is you cwd and hence user demo didnt had permission to access /root.
    – Sagar
    Sep 28, 2017 at 18:15
  • @Christopher I refined that part.
    – Kusalananda
    Oct 2, 2017 at 20:43
2

Don't use - (hyphen) after su. Simply run
su demo -c 'ls -la'
When you invoke '-' with su, It initializes user profile and environment. There must be some script within profile which is not letting user shell to reach at the end.

Not the answer you're looking for? Browse other questions tagged .