Ubuntu: chmod only certain mime-types


I'm using file --mime-type * to find the mime-types of all files in a selected directory.

Many of these files should not be executable and are .conf or their type is text/plain. Is there a combination of the find command that can change all non-executable mime-types back to 644 instead of 755?


You could use something like that:

file -F' ' --mime-type * | awk '$2 ~ /text\/plain/{print $1}' | xargs chmod 644  

This changes all permissions to 644 if a file has the mime-type text/plain. Just replace the part in the awk body to whatever mime-type you wish. See /etc/mime.types for all available ones.


  • The -F' ' flag causes file to use a space as separator between the filename and the result. It's easier for the later awk statement
  • The awk part prints only the name of the file if the second field ($2) of the output contains text/plain.
  • xargs calls chmod 644 on every item


Below, the file --mime-type command used in a python script. It changes the permissions of the file types(s) you define to the 'new_permissions', in a given directory (recursively).

#!/usr/bin/env python3    import subprocess  import os    directory = '/path/to/files'  m_subject = ('text/plain', 'another_mimetype')  new_permissions = '644'    for root, dirs, files in os.walk(directory):      for file in files:          check_mtype = 'file --mime-type '+'"'+root+'/'+file+'"'          mtype = subprocess.check_output(              ['/bin/bash', '-c', check_mtype]).decode('utf-8').strip().split(' ')[-1]          if mtype in m_subject:              set_permissions = 'chmod '+str(new_permissions)+' '+root+'/'+file              subprocess.Popen(['/bin/bash', '-c', set_permissions])              print('permission set to '+new_permissions+' '+root+'/'+file)  

Copy the script into an empty file, in the head section of the script, set the directory, the mime-types to change and the new permissions, save it as change_types.py.

Run it by the command:

python3 /path/to/change_types.py  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »