Fernando
Fernando

Reputation: 3

BashScript - Sudo as a user, enter in a certain folder and run a command

I'm a newbie to Bash Script, I've been trying to sudo as a certain user, enter in a specific folder and run a command. I tried this command below:

#!/bin/bash
sudo -i -u "site"  cd /home/site/public_html && pwd

or

#!/bin/bash
sudo -i -u "site" cd /home/site/public_html
sudo -i -u "site" pwd

The first one just enters as the user enters in the folder, leaves and send a pwd on my own user The second one enters as the user enters in the folder, leaves, enters as the user and send a pwd

Any help will be welcome! Thank you!

Upvotes: 0

Views: 818

Answers (1)

Barmar
Barmar

Reputation: 781096

Each sudo command starts a new shell process, so process changes done by one command have no effect on the next one.

You need to run everything in a single shell process. You can do this by running bash explicitly.

sudo -i -u "site" bash -c 'cd /home/site/public_html && pwd'

Upvotes: 1

Related Questions