How to control default permission on copy file unix

289 views Asked by At

I have executed a shell script in which I have copied a file as root user in another user as:

cp myFile.txt /opt/another_user/some_dir/

The file permissions in that user are -rw-r--r-- but I have the replica of this machine, where I executed the same command but the permissions of file are -rwxr-x---.

Why this default permission is different in 2 machines. Whether we set some rules while creating the user.

2

There are 2 answers

0
John3136 On

RTFM. Specically the umask FM, via man umask

You may also want to check what your chosen shell's manual page says about umask.

0
Yd Ahhrk On

To ellaborate a bit on John3136's answer:

There's this thing called "file mode creation mask." Each shell has its own (ie. if you change it and open a new terminal, the new terminal gets the default value), and it's a chmod-type permission string which is subtracted from new files.

You can print yours by running umask:

$ umask
002
$ umask -S
u=rwx,g=rwx,o=rx

As you can see, mine subtracts the "other write" bit:

$ chmod 777 tmp
$ cp tmp tmp2
$ ls -l tmp2
-rwxrwxr-x 1 ahhrk ahhrk 0 may 19 10:55 tmp2*

Here's umask's generic POSIX documentation. Note that your implementation might unlikely be slightly different. On Ubuntu, I found my specific umask documentation in man 1 bash, not man umask. (The latter leads to man 2 umask, which refers to the umask() system call, which has little to do with our purposes.)

Slightly more ellaborate example:

$ # remove read from user, write from group and execute from other
$ umask 421
$ cp tmp tmp3
$ ls -l tmp3
--wxr-xrw-  1 ahhrk ahhrk       0 may 19 11:03 tmp3*

So maybe one of your file mode creation masks is removing the execute bits.