Linux – Give execution permission to directories but not to files

bashchmodfile-permissionslinux

I have a directory structure with files and directories and I like to assign permissions so all the files and directories have read-write permissions for the user and read permissions for the group and, additionally, execution permissions to the directory.

I would like to achieve something like that:

$ ls -l
total 16
-rw-r----- 1 daniel daniel    0  5月 23 16:20 1
-rw-r----- 1 daniel daniel    0  5月 23 16:20 2
-rw-r----- 1 daniel daniel    0  5月 23 16:20 3
-rw-r----- 1 daniel daniel    0  5月 23 16:20 4
-rw-r----- 1 daniel daniel    0  5月 23 16:20 5
drwxr-x--- 2 daniel daniel 4096  5月 23 16:00 a
drwxr-x--- 2 daniel daniel 4096  5月 23 16:00 b
drwxr-x--- 2 daniel daniel 4096  5月 23 15:59 c
drwxr-x--- 2 daniel daniel 4096  5月 23 15:59 d

Best Answer

To give execution (search) permission to directories, but not to files, use:

chmod -R +X .

To assign all the permissions as in your example, use:

chmod -R u=rwX,g=rX,o= .

-R changes files and directories recursively, while +X sets execute/search only if the file is a directory or already has execute permission for some user. r and w are of course for reading and writing, respectively.

Mode X (upper x) is documented in both the traditional manual page1 and the info documentation2.

It should also work on other Unix like systems, e.g. FreeBSD, NetBSD or OpenBSD. Quoting from the chmod(1) man page of The Open Group Base Specifications Issue 7, 2018 edition:

The X perm symbol was adopted from BSD-based systems because it provides commonly desired functionality when doing recursive (-R option) modifications. Similar functionality is not provided by the find utility. Historical BSD versions of chmod, however, only supported X with op+; it has been extended in this volume of POSIX.1-2017 because it is also useful with op=. (It has also been added for op- even though it duplicates x, in this case, because it is intuitive and easier to explain.)


1 man 1 chmod
2 info '(coreutils)Conditional Executability'

Related Question