How to Copy Files & Directories as a Sudo User

I login to linux using my Id eg "A". then i'll sudo to the user 'B' without entering the password, after that i'll copy some files from X folder to Y Folder using the SUdo user 'B'.

I am trying to do this activity with a shell script to put it in the cronjob... so far no luck.

Any help on this will be really appreicate...

this is what i am trying...

#!/bin/sh
sudo /usr/local/sbin/deploy
cp -r /tmp/test /tmp/deploy
3

4 Answers

You must run the cp with sudo as well. Otherwise, deploy creates the files with owner B and then, the cp can't read them (since the shell returns you to the original user when the sudo in your script completes).

Alternatively, run chmod with sudo to make the files readable for A and then make a copy.

sudo only runs the command on the commandline, then returns you back to the invoker's account. if you want to run multiple commands as another user, it would be better to create a script and run that script via sudo.

sudo is an interactive command. Using it in cron jobs does not make sense. Either you create a super user script to copy all the files and then change the ownership, or run the script by the required user itself.

Try this: for example if your username is "james", add the following entry to the /etc/sudoers or into a separate /etc/sudoers.d/ file. After this, you can copy files from source to target without entering password.

# visudo 
james  ALL=(ALL) NOPASSWD: /bin/cp

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Sophia Al-Mansoor

Sophia Al-Mansoor

Global Business & E-Commerce Reporter

Sophia analyzes international trade, startup ecosystems, retail transformation, and supply chain logistics for modern digital publications.

Share this article
Twitter Facebook Pinterest