3

I need to run two or more commands as another user in Linux. For example, using "root", I need to sudo to another user and do something like "cd /tmp/; ls -ltr".

If I do: "sudo -i -u john.smith whoami" without the double quotes, it will tell me I am john.smith.

Now I want to expand that do whoami, change directories, and execute an ls command while using "root" to sudo as john.smith.

3
  • 1
    Can you clarify what you want? Commented Dec 8, 2016 at 17:14
  • 2
    Make a script and run that? Commented Dec 8, 2016 at 17:16
  • Sorry, I should have clarified that I want to try this without writing a script. Eventually I want to be able to update the command on the fly with our automation scheduler without having to log into the server and update the script. That way, others would be able to do the same if I'm unavailable. Commented Dec 8, 2016 at 17:39

2 Answers 2

5

Bash supports a -c flag that lets you specify the command to run as a command-line argument — basically an inline Bash script. That means you can easily combine multiple commands into a single call to bash, which is then easily sudo-ed:

sudo -i -u john.smith bash -c 'whoami ; cd /tmp/ ; ls -ltr'

or

sudo -i -u john.smith \
  bash -c ' whoami
            cd /tmp/
            ls -ltr
          '

(Other shell languages have the same feature.)

Sign up to request clarification or add additional context in comments.

Comments

0

You can make small shell script file and start it with sudo.

Another thing I often useon Ubuntu is to make "sudo su" - this give me root shell and I proceed from there.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.