What is chmod?
When I started building applications or developing scripts for automation in Linux environment, I came across a keyword “chmod” to give permissions for the files to execute, read or write depends on the scenario. In this article, we will look into the usage of chmod and its parameters.
chmod
This is a command in Linux/Unix distribution to change the attributes and give permissions to a file/folder.
Linux chmod command, file permissions and bash scripts
The Linux chmod command is the tool that is used to set file access permissions in a Linux system, along with most other POSIX systems for that matter. The chmod command can be used with other commands such as ls -l to find out what the current state is with permissions, and do something to change that state.
The chmod command also comes into play when it comes to making a bash script, or any script execute without having to call the command to do so first. When working out a script for automating work there is placing a shebang at the top of the file to let Linux know what binary needs to be used to run the script. However in order to make use of it the script needs to become executable first, and one way to do that is by using the Linux chmod command.
1 — Using the Linux ls -l command to check status of permissions before using chmod
Before using the Linux chmod command to change file access permissions it is first necessary to check the current status of file access permissions. One simple command for doing to is the Linux ls command with the -l option to print a long from of all and any files found.
Using the ls -l option for the current working path
Using Linux ls -l for a single file
The thing to look at hear is what is going on with the collection of r, w, and x chars at the beginning of each line of the output. The char r stands for read, w is for write, x is for execute, and — means no permission. There are three sets of these values from, and from right to left the sets of three chars are for the owner of the file, the owner group, and everyone else.
Now that we know how to check file access permissions we can not use chmod to change these values.
2 — Chmod and Octal modes
The best way to go about using chmod is to call the command followed by a set of three octal digits. So each digit has a range between 0 and 7 where 0 means no permission of any kind, and 7 means full permission.
3 — Making a script executable, or not, with +x and -x
One thing that I often find myself doing is using chmod to make a script that I wrote executable. Often a script is very much executable before hand, it is just that I need to call the binary that is used to run it first, and then pass the script I want to run as an argument to that binary. So what I really mean here is to make it so the script can just be run directly by making use of the proper shebang at the top of the script.
A shebang is a line at the very top of a script that serves one simple purpose to inform bash where the binary is to use to run the script. With a nodejs script, a shebang would look something like this:
Which should be the path for the nodejs binary that is needed to run a script that is written in javaScript. However this shebang is only really needed when it comes to making it so the script can be run directly. I can always just call node in the command line to run the script, but if I want to run the script by itself I need a way to let bash know where the binary is for this script file. So in this section I will be going over the use of the chmod command to make it so a script is executable.
3.1 — start with a script
First off I need a script to check permissions for, and set to the proper permissions. Also the script should have the proper shebang at the top of the file. For this example I will be sticking to bash, and make a simple bash script that just uses echo to print hello world to the standard output.
3.2 — calling the script with the binary
So now that I have a basic bash script there is the question of how to go about calling it. With that said because it is a bash script I can just call the bash command directly and then pass the bash script as an argument to the bash command.
Although this will work it defeats the purpose of adding the shebang at the top of the file. The shebang is there to let Linux know where the binary is to run this script after all. So if I am just directly calling the script with bash what is the point of having the shebang there?
So the shebang is there so I can just go ahead and run the script, but there is a problem when doing so.
The current user does not have permission to run the script. Assuming that the current user has the authority to change the status of the file access permissions of the script, all that needs to happen is to just change the permissions of the script so that it can be execute for the current user. This is where the chmod command comes into play, there are a few ways to do about setting the permissions for executing a script, not just for the current user, but everyone.
3.3 — Checking status of script, and making it executable with chmod +x
So to check the status of basic.sh I just need to use the ls -l command to check the permissions of the file.
When doing so I can see that the current user has read and write access, but does not have permissions to run the file. To change that I just need to use chmod +x.
This makes it so the script can be run for the current user, but it also makes it executable for all users in the current group, and everyone for that matter. So then there is the question of how to go about setting the status of this back, and there is also the question of how to have more fine grain control over this. So with that said lets look at just a few more chmod examples.
3.4 — Make the script NOT executable any more with chmod -x
So now say that I have an executable script, and I want to make it so it can no longer be executed. To set things back to the way they where I just need to use the chmod -x command.
Simple enough, we are now back to where we were. However what if I just want to make it so the current use can run the script, but not any other user, except for root or course. Well octal modes do help to give better control over this, and all other values for that matter.
3.5 — Using octal modes to set just the values that are wanted
Although the +x, and -x options for Linux chmod are convenient, they are no substitute for the fine grain control over file access permissions that is gained by using octal modes. An octal mode is just simply a set of three octal digits for each group to which file access permissions apply, the owner, the owners group, and everyone. An octal digit of 7 will mean to read, write, and execute. So if I want the owner of the file to have all permissions, then I will want to start off the set of digits with 7. After that I will want to set lower values for all other groups, such as 4 which would be read only.
4 — Conclusion
The chmod command is one of many little commands that come up when it comes to learning how to become more professorial when it comes to using Linux. Often the default permissions that are set when creating and editing a file work just fine, but often I might have to adjust them. For example say I have more than one user for a system, and I want to have the same permissions for all files in the home folder. The Linux chmod command along with ls -l are the basic tools that I need to know about in order to make those adjustments.
Команда chmod Linux
Система полномочий в Linux имеет очень важное значение, поскольку благодаря ей можно разделять привилегии между пользователями, ограничить доступ к нежелательным файлам или возможностям, контролировать доступные действия для сервисов и многое другое. В Linux существует всего три вида прав — право на чтение, запись и выполнение, а также три категории пользователей, к которым они могут применяться — владелец файла, группа файла и все остальные.
Эти права применяются для каждого файла, а поскольку все в системе Linux, даже устройства, считаются файлами, то, получается что эти права применимы ко всему. Мы более подробно рассматривали как работают права доступа к файлам Linux в отдельной статье, а этой, я хочу остановиться на команде chmod, которая используется для установки прав.
Команда chmod Linux
Эта команда имеет типичный для команд linux синтаксис, сначала команда, затем опции, а в конце файл или папка, к которой ее нужно применить:
$ chmod опции права /путь/к/файлу
Сначала рассмотрим какими бывают права доступа linux и как они устанавливаются. Пред этим рекомендую прочитать статью про права, ссылка на которую есть выше. Есть три основных вида прав:
- r — чтение;
- w — запись;
- x — выполнение;
- s — выполнение от имени суперпользователя (дополнительный);
Также есть три категории пользователей, для которых вы можете установить эти права на файл linux:
- u — владелец файла;
- g — группа файла;
- o — все остальные пользователи;
Синтаксис настройки прав такой:
группа_пользователей действие в ид_прав
В качестве действий могут использоваться знаки «+» — включить или «-« — отключить. Рассмотрим несколько примеров:
- u+x — разрешить выполнение для владельца;
- ugo+x — разрешить выполнение для всех;
- ug+w — разрешить запись для владельца и группы;
- o-x — запретить выполнение для остальных пользователей;
- ugo+rwx — разрешить все для всех;
Но права можно записывать не только таким способом. Есть еще восьмеричный формат записи, он более сложен для понимания, но пишется короче и проще. Я не буду рассказывать как считать эти цифры, просто запомните какая цифра за что отвечает, так проще:
- 0 — никаких прав;
- 1 — только выполнение;
- 2 — только запись;
- 3 — выполнение и запись;
- 4 — только чтение;
- 5 — чтение и выполнение;
- 6 — чтение и запись;
- 7 — чтение запись и выполнение.
Права на папку linux такие же, как и для файла. Во время установки прав сначала укажите цифру прав для владельца, затем для группы, а потом для остальных. Например, :
- 744 — разрешить все для владельца, а остальным только чтение;
- 755 — все для владельца, остальным только чтение и выполнение;
- 764 — все для владельца, чтение и запись для группы, и только чтение для остальных;
- 777 — всем разрешено все.
Каждая из цифр не зависит от предыдущих, вы вбираете именно то, что вам нужно. Теперь давайте рассмотрим несколько опций команды, которые нам понадобятся во время работы:
- -c — выводить информацию обо всех изменениях;
- -f — не выводить сообщения об ошибках;
- -v — выводить максимум информации;
- —preserve-root — не выполнять рекурсивные операции для корня «/»;
- —reference — взять маску прав из указанного файла;
- -R — включить поддержку рекурсии;
- —version — вывести версию утилиты;
Теперь, когда вы знаете опции и как настраиваются права доступа chmod, давайте рассмотрим несколько примеров как работает команда chmod linux.
Примеры использования chmod
Я не буду приводить много примеров, так как там и так все более-менее понятно после пояснения правил создания выражений установки прав. Сначала самый частый случай — разрешить выполнения скрипта владельцу:
Или можно воспользоваться цифровой записью:
chmod 766 file
ls — l file
Недостаток цифровой записи в том, что вы не можете модифицировать уже существующие права доступа linux. Например, в первом варианте вы просто добавили флаг выполнения для владельца файла, а все остальные права оставили неизменными. В восьмеричном варианте мы полностью заменили текущие права новыми — все для владельца и чтение/запись для группы и остальных. Как видите, права установлены как и ожидалось. Теперь отключим выполнение владельцем:
И снова проверяем:
Дальше разрешим только чтение всем, кроме владельца:
chmod 744 file
ls -l file
Или отберем все права:
chmod ugo-rwx file
Файлы с правами 000 недоступны никаким пользователям, кроме суперпользователя и владельца. Вернем права обратно:
chmod 755 file
ls -l file
Такая же ситуация с файлами, владельцем которых вы не являетесь, если вы хотите изменить их права — используйте sudo. Из модификаторов прав вы можете конструировать любые последовательности, я думаю тут нет смысла разбирать их все. Для того чтобы поменять права на все файлы в папке используйте опцию -R:
chmod -R ug+rw dir
ls -l dir/
Также вы можете смотреть подробную информацию про вносимые изменения, например:
chmod -Rv ug+rw dir
Выводы
В этой небольшой статье была рассмотрена команда chmod linux. Она очень часто используется наряду с такими командами, как chown и umask для управления правами. Надеюсь, эта информация была полезной для вас. Если у вас остались вопросы, спрашивайте в комментариях!
Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.
“chmod +x” explained – everything you need to know
Do you want to know what does “ chmod +x ” means in Linux?
chmod is a very useful command, made to manage file modes in Linux.
Each file and directory in Linux can hold three types of permissions: read ( r ), write ( w ), and execute ( x ). Each permission may be on or off for each of three categories of users: the file or directory owner; other people in the same group as the owner; and all others.
One of the most used chmod command is chmod +x which uses +x switch to modify the execution permission. In this article we are going to show you different use cases for user or owner, group and others roles.
What does chmod +x do?
In short, chmod +x following by a filename, usually a script, means that you make it executable.
In Ubuntu or other distro that uses GNOME, you can achieve the same result by right click on your file/script and choose Properties, then switch to Permissions tab, tick the Allow executing file as program checkbox.
Operation not permitted error with chmod?
Running any chmod command, include chmod +x usually produces no response. But in some cases, you will encounter this error : chmod: changing permissions of ‘/usr/share/test/path’: Operation not permitted .
The error means you do not have the rights to change permission on /usr/share/test/path , which is a system directory. In this case, you must use your root privileges through sudo command (but be careful as sudo has the ability to break your system).
If you see no response, the command ran successfully and the permissions have been changed.
chmod u+x versus chmod +x comparison
A huge number of tutorials on the internet use chmod u+x in their tutorials for demonstration purpose. If you actually run chmod u+x and compare with chmod +x , you should see no difference in most cases.
- u stands for user.
- g stands for group.
- o stands for others.
- a stands for all.
That means that chmod u+x filename will grant the execution permission to the owner of the file and no one else, whereas chmod +x filename is the same as chmod a+x filename (which means give everyone the rights to run the file).
chmod +x vs chmod 777 comparison
Instead of using ugoa shorthand for permissions, chmod allows you to use numbers, which is called octal mode number notation .
- r (read) = 4
- w (write) = 2
- x (execute) = 1
- To represent rwx triplet use 4+2+1=7
- To represent rw- triplet use 4+2+0=6
- To represent r– triplet use 4+0+0=4
- To represent r-x triplet use 4+0+1=5
- chmod +x is equal to chmod a+x , which means “add executable permission to somefile for all user groups”
- chmod 777 is equal to chmod a=rwx , which means “set read, write, executable permission to somefile for all user groups”
These commands usually produce the same results, but in reality they are fundamentally different.
chmod +x FAQ
We’ve collected a bunch of frequently asked questions. Please review them carefully before you ask any other.
- How to set executable permission to a file for user?
We can use +a in order to give all users regardless of their groups the execution right to a file. For example: enable execution permission of script.sh for all users : chmod a+x script.sh
4 thoughts on ““chmod +x” explained – everything you need to know”
Nice explanation for beginners. I am a beginner, I understood this concept without any doubt.