Score:0

Shell Script to Move a File Into Another User's Directory?

ca flag

I'm running a Ubuntu 16.04 server. On my server, I have a file in directory /home/userA/dirA:

userA@myUbuntu:~$ 
userA@myUbuntu:~$ pwd
/home/userA
userA@myUbuntu:~$ 
userA@myUbuntu:~$ ls -l
total 8
drwxrwxr-x 3 userA userA 4096 Feb 17 14:13 dirA
userA@myUbuntu:~$ 
userA@myUbuntu:~$ ls -l dirA/
total 7796
-rw-rw-r-- 1 userA userA  1234 Feb 17 14:05 theFile.txt
userA@myUbuntu:~$

Note the ownership here; user userA owns the file and the directory where the file resides.

I need a shell script that moves theFile.txt to another location, into a directory that is not owned by userA. Here's my script:

#!/bin/bash
echo "Attempting to move file..."
{
        sudo mv /home/userA/dirA/theFile.txt /home/userB/dirB/.
} || {
   echo "Failed to move file!"
}

...and the output:

userA@myUbuntu:~$ ./myScript.sh
Attempting to move file...
Failed to move file!
userA@myUbuntu:~$ 

As you can tell, the script runs as userA. I don't want to run it as root.

So I'm assuming the script is failing because of the permissions; a script run as userA does not have permission to move a file into a directory owned by userB. I've been trying all sorts of variations of the sudo command and others, but to no avail. I've also tried goofy workarounds, like copying the file to /tmp (that works) and then doing a chown to change file ownership (that doesn't work). But there's got to be a way to neatly do this. Any ideas?

FULL DISCLOSURE :: I've also posted this question here.

Score:0
ca flag

Solution provided here.

Both userA and userB must be added into a common user group. Then, the permissions of all directories in path for the target directory must be assigned to this group. Additionally, you have to set "chmod 777" for each directory along the way.

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.