2

Does anyone know how to set the default permissions if a user makes a new file, the file will have -rwxrw-r—permission.

1 Answers1

2

Disclaimer: As some users have commented, automatically creating files with executable permissions breaks a significant part of the Linux security model.

That said there is a way to achieve what you want, on the command line and to limit which users can do this.

You could write a function to create the file and modify the permissions at the same time. This function should be added to each users .bashrc file. This file can be found at /home/username/.bashrc.

Here's an example to make a function called createafile, The lines to add would be:

createafile() {
if [[ -z $1 ]]; then
  echo "Cannot create a file with no name!"
  return 1
elif [[ -e $1 ]]
  echo "That file already exists!"
  return 1
elif [[ $2 = -* ]]; then
  echo "Permissions must not start with a '-'!"
  return 1
fi
touch $1
if [[ -z $2 ]]; then
  perms=764
else
  perms=$2
fi
chmod $perms $1
}

Once this is written into a user's .bashrc file, they must log out and back in before it can be used. The function can be called on the command line like so.

createafile newfile.txt

Which will create the file with your default octal permissions of 764, or -rwxrw-r--. Alternatively if you want to specify a different permission mode you can enter this in any recognised format for the chmod command. So to make a file with read/write permission for everyone

createafile anotherfile.txt 555

or

createafile anotherfile.txt a+rw

This function will complain and exit if the file already exists, or if you don't enter a filename. The function will not work if the user doesn't have the appropriate directory permissions to write the file or change permissions.

There's a line in the function that stops users entering a chmod option accidentally. This does mean that you can't use the permission removal functionality of chmod where the permissions start with a - character.

Arronical
  • 19,893
  • It's my first .bashrc function! Glad you like it ^_^. I'm a bit worried about the possibility of passing a chmod option accidentally but couldn't work out the regex to see is there's a dash at the start of line. – Arronical Aug 25 '16 at 11:44
  • Good catch. -R is pretty useful, but there are a lot of errors made by newer users, when they blitz /usr/bin or come other necessary directory with wrong perms! – Arronical Aug 25 '16 at 12:00
  • 1
    Yeah, I see what you're saying, and that's generally how I end up using it. It's normally in `/var/www/html for web stuff, but you do always end up fixing directory perms afterwards. That gives me an idea for another function! – Arronical Aug 25 '16 at 13:29
  • 1
    Did this answer help at all @ForestAmp ? – Arronical Aug 31 '16 at 14:29